问题
I'm having some issues with the Entity Framework using POCOs and I hope someone can tell me at a high level if the behaviour I'm seeing is expected or I need to dig deeper into why it's happening.
I have a class Customer
and another CustomerType
, so Customer
has a property Type
(of type CustomerType
indicating the type) and CustomerType
has property Customers
which is a collection of Customer
s (All Customer
s that have that type) So these are basically the Navigation properties on both ends of an association, resulting in POCO code something like:
public partial class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public CustomerType Type { get; set; }
}
public partial class CustomerType
{
public CustomerType()
{
this.Customers = new HashSet<CustomerType>();
}
public int Id { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
I have turned off Proxy creation and LazyLoading (i.e. both DbContext.Configuration.ProxyCreationEnabled=false
and DbContext.Configuration.LazyLoadingEnabled=false
) because they make Serialization a pain.
As expected when I get instances from the Customer
set, the Type
property on them is null by default.
But if I get instances from the Customer
set with a .Include("Type")
not only is it loading the Type
properties, but it's also loading the children - i.e. the collection of Customer
s on each of these.
Is this expected?
回答1:
It is semi expected. The Include extension affects the SQL that is run. Those CustomerTypes that ARE loaded (by virtue of being included in the Customer query) will be built into the object tree according to the CustomerType.ParentId column.
So if by some fluke both a parent and a child is loaded in the same query, the child will be stuffed into the parent.
来源:https://stackoverflow.com/questions/16534309/entity-framework-with-proxy-creation-and-lazy-loading-disabled-is-still-loading