Search code examples
c#linq-to-sqlinheritancedatasourceoftype

Linq2SQL inherited types and OfType query


I have a setup where I used Linq2SQL inheritance. To make queries easier, I expose the derived types in the DataContext as well, like the following:

public IQueryable<Derived> Derivations 
{
  get { return Bases.OfType<Derived>(); } // filter list on type
}

Calling this works perfectly, and I can see the SQL being correctly generated. The backing type is DataQuery<T>.

The problem comes in when I assigning this IEnumerable to a datasource (either a control or a BindingSource).

From what I can see, the DataQuery object is queried for an IListSource. And it happily supplies this. Then it proceeds to make a BindingList, which fails as the type parameter of the 2 arguments supplied (IEnumerable<Derived> and Table<Base>) does not match. It raises an exception of MissingMethod as the constructor cannot be found.

The simple workaround is just to call ToList() on the IQueryable<Derived> before assigning to the datasource and then it works, but this is quite tiring.

Any suggestions to handle this without 'loosing' the IQueryable?

Thanks

leppie

UPDATE:

The bug has now been reported to MS. More details here. Thanks Marc!


Solution

  • Confirmed. Looks like a bug to me; you should log it on Connect. The team are fixing LINQ-to-SQL bugs, so it might not be ignored. For now, use .ToList() etc.

    Sample code:

    using (var ctx = new MyDataContext())
    {
        var qry = ctx.BaseEntities.OfType<DerivedEntity>();
        IListSource ls = (IListSource)qry;
        IList list = ls.GetList(); // boom
        /* Constructor on type
           'System.Data.Linq.Provider.DataBindingList`1[snip]'
           not found.*/
    }