Entity Framework does not request derived classes - Error in DbOfTypeExpression

I have a base class and two derived classes.

Each of the derived classes implements the same type as the property - the only difference is the name of the property.

Unfortunately, I do not greatly influence the design of the class - → they were created from the wsdl file.

Then I have a BaseType property to encapsulate a common property. The plan was to use this property in my web views, etc.

I used the famous "Fruit Example" to demonstrate the problem:

 public class FruitBase
    {
        public virtual int ID { get; set; }


        //
        // The plan is to use this property in mvc view
        //
        [NotMapped]
        public virtual FruitnessFactor Fruitness
        {
            get
            {
                if (this.GetType().BaseType == typeof(Apple))
                    return ((Apple)this).AppleFruitness;
                else if (this.GetType().BaseType == typeof(Orange))
                    return ((Orange)this).OrangeFruitness;
                else
                    return null;
            }
        }
    }

public class FruitnessFactor { }

In my MVC controller, the following query works absolutely fine:

return View(context.FruitEntities
                           .OfType<Apple>().Include(a =>a.AppleFruitness)
                           .ToList());

But this is not:

  return View(context.FruitEntities
                                   .OfType<Apple>().Include(a =>a.AppleFruitness)
                                   .OfType<Orange>().Include(o => o.OrangeFruitness)
                                   .ToList());

The error message I get is:

DbOfTypeExpression requires an expression argument with a polymorphic result type that is compatible with the type argument.

EF 5.0 RC Code First.

!

+5
1

, Include . (OfType<Apple>().Include(a => a.AppelFruitness)) . , , ( ).

- - .

( ) - . ( )...

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

... :

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();

( AsNoTracking), , ( " " ), , viewModel...

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

... , FruitnessFactor.

, :

+7

All Articles