How to load only the base type in the Entity Framework

Consider the following case:

I have a base class inherited by two others. For example, we will have:

class Base { } class DerivedA : Base { } class DerivedB : Base { } 

When I request a base object with type code

context.Base.Where (q => q.Id == id) .First ();

Entity Framework generates a complete set of joins for each derived object, which reduces the acceptable execution of the query. That I want to load only the base object without attaching it to the derivatives.

The only solution I found described here is http://blogs.msdn.com/b/alexj/archive/2009/09/17/tip-35-how-to-write-oftypeonly-tentity.aspx . But that did not work for me. EF still generates a huge request.

Writing queries such as:

 context.Base.Where(q => !(q is DerivedA) && !(q is DerivedB)).First(); 

not suitable for me due to the ever-increasing number of derived types.

Are there any possible solutions besides the ones I mentioned?

+4
source share
2 answers

You use Table-per-type => EF must generate these joins because it does not know what type your object is actually. If your entry from Base has a corresponding entry in the DerivedA table IT MUST NOT create an instance of the Base object for this record - IT MUST create an instance of DerivedA , and it needs to create connections to obtain this knowledge.

This is a long discussion of why this is not allowed, but just an object from the object world is an atomic data structure that can be stored in several tables, but invisible to the world object. If you save Base , you load Base back, but if you save DerivedA , you will always load DerivedA back and never just Base , because that will break the atomicity of the object.

I have not tried it, but I assume that the ESQL OFTYPE ONLY should also perform joins to make sure that it really loads real instances of the underlying object instead of corrupted instances of the derived objects.

A table for each type produces slow queries..NET 4.5 should improve it, but I think that the improvements will not be targeted at these cases - I think that they will be targeted at OfType for derived types and forecasts.

If you only need data from the Base table, your best options are:

+5
source

You can introduce an abstract intermediate class without any additional values ​​/ functions from which all derived types should be derived:

 class Base { } abstract class DerivedBase : Base { } class DerivedA : DerivedBase { } class DerivedB : DerivedBase { } 

Then you can make a simple query, not counting how many derived classes exist:

 context.Bases .Where(b => !(b is DerivedBase)) ... 
0
source

All Articles