Entity Framework doesn't query derived classes - Error in DbOfTypeExpression

China☆狼群 提交于 2019-12-05 05:16:48
Slauma

As far as I can tell you can't apply Include on multiple subtypes in a single database query. You can query one type (OfType<Apple>().Include(a => a.AppelFruitness)) and the same for another subtype. The problem is that you can't concat the results in the same query because the result collections have different generic types (apples and oranges).

One option would be to run two queries and copy the result collection into a new collection of the base type - as you already indicated in the comment section under your question.

The other option (which would only need a single query) is a projection. You would have to define a projection type (you could also project into an anonymous type)...

public class FruitViewModel
{
    public FruitBase Fruit { get; set; }
    public FruitnessFactor Factor { get; set; }
}

...and then can use the query:

List<FruitViewModel> fruitViewModels = context.FruitEntities
    .OfType<Apple>()
    .Select(a => new FruitViewModel
    {
        Fruit = a,
        Factor = a.AppleFruitness
    })
    .Concat(context.FruitEntities
    .OfType<Orange>()
    .Select(o => new FruitViewModel
    {
        Fruit = o,
        Factor = o.OrangeFruitness
    }))
    .ToList();

If you don't disable change tracking (by using AsNoTracking) the navigation properties get populated automatically when the entities get attached to the context ("Relationship fixup") which means that you can extract the fruits from the viewModel collection...

IEnumerable<FruitBase> fruits = fruitViewModels.Select(fv => fv.Fruit);

...and you'll get the fruits including the FruitnessFactor properties.

This code is pretty awkward but a direct approach without using a projection has been asked for several times without success:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!