1

Using Visual Studio's O/R Designer, I have created a number of classes the inherit from a base class (named SCO).

The inherited types have a discriminator property TypeId which is a string containing the name of the type. For example, the inherited class Blog would have a TypeId property of Blog.

I want to be able to create a method that returns a strongly typed collection of any of the particular inherited types. My attempt at this method is as follows:

public static IQueryable<T> GetSCOs<T>(SCODataContext dc) where T : SCO
{
    string targetType = typeof(T).Name;
    IQueryable<T> scos = from s in dc.SCOs
                         where s.TypeId == targetType
                         select s;
    return scos;
}

When I try and compile this method, I get the following error...

_Cannot implicitly convert type 'System.Linq.IQueryable<SCOs.SCO>' to 'System.Linq.IQueryable<T>'. An explicit conversion exists (are you missing a cast?)_

I (think) I understand why this is happening, but have been unable to find a solution. Any advice, guidance would be much appreciated.

2
  • 2
    Please mark the answer as accepted if it solves the problem, this prevents other users from adding more answers that might be wrong and also helps others looking for answers to find your question instead of asking their own. Commented Dec 22, 2010 at 9:47
  • The thing people forget when using generics is that they need to be known at compile time otherwise the compiler can't guarantee type safety (which is the whole point of using generics). LINQ queries on the other hand are run JIT so the method you are using creates some problems for the compiler, hence the IQueryable<T> in your error message. Commented Dec 22, 2010 at 11:25

1 Answer 1

7

Try this:

public static IQueryable<T> GetSCOs<T>(SCODataContext dc) where T : SCO
{
    return dc.SCOs.OfType<T>();
}

Works for LINQ-Entities, not sure if it works for LINQ-SQL. Give it a try.

Sign up to request clarification or add additional context in comments.

2 Comments

This is awesome. I was going to answer with "dc.SCOs.Where(s => s is T).Cast<T>();" but this is better!
Sweet - i had a feeling it would work, since the method is from the LINQ-Objects API. Don't forget to tick this the correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.