实体框架代码优先 - 渴望加载不按预期工作?

djd*_*d87 11 linq-to-entities code-first entity-framework-4 c#-4.0

我有以下Entity Framework POCO类:

public class Customer
{
    public int Id {get;set;}
    public string Name {get;set;}

    public virtual ICollection<Order> Orders {get;set;}
}

public class Order
{
    public int Id {get;set;} 
    public int CustomerId {get;set;}
    public int OrderTypeId {get;set;}

    public virtual OrderType Type {get;set;}
    public virtual Customer Customer {get;set;}
} 

public class OrderType 
{
    public int Id {get;set;}
    public virtual ICollection<Order> Orders {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我返回我的时候,我ICollection<Order>Orders正常,但是它的OrderType属性Order没有被填充.我的订单将包含以下详细信息:

Id:          1
CustomerId:  1
Customer:    Populated
OrderTypeId: 3
Type:        null        // Never returned
Run Code Online (Sandbox Code Playgroud)

我的映射代码如下所示:

public void ConfigureOrder(ModelBuilder builder)
{
    // Mapping from Order -> Customer
    builder.Entity<Order>()
        .HasRequired(x => x.Customer)
            .WithMany(x => x.Orders)
                .HasConstraint((order, cust) => order.CustomerId == cust.Id);

    // Mapping from Order -> OrderType
    builder.Entity<Order>()
        .HasRequired(x => x.OrderType)
            .WithMany(x => x.Orders)
                .HasConstraint((order, type) => order.OrderTypeId == type.Id);
}
Run Code Online (Sandbox Code Playgroud)

然后我在我的上下文中禁用了Lazy加载:

public Context(string connectionString)
    : base(connectionString)
{
    ObjectContext.ContextOptions.LazyLoadingEnabled = false;
}
Run Code Online (Sandbox Code Playgroud)

所以要在我的存储库中返回数据,我使用以下Include方法System.Data.Entity:

var query = from item in context.Customers
                .Include(x=> x.Orders)
            where item.Id == customerId
            select item;
Run Code Online (Sandbox Code Playgroud)

我假设因为我无法指定Orders.OrderType,这就是问题,所以我尝试了一些变化:

1 -> .Include(x=> x.Orders.FirstOrDefault().OrderType)
2 -> .Include("Orders")
3 -> .Include("Orders")
     .Include("Orders.OrderType")
Run Code Online (Sandbox Code Playgroud)

但我永远无法返回OrderType属性,除非我直接加载Order:

var query = from item in context.Orders
                .Include(x=> x.OrderType)
            select item;
Run Code Online (Sandbox Code Playgroud)

此代码将正确返回订单中的OrderType.

djd*_*d87 22

噢亲爱的.看起来我是一头驴.现在是17:45,我现在应该回家了.

我有两个Get方法:

Get(int customerId)
{
    // This was the method I was testing within
    var query = from item in context.Customers
                    .Include("Orders.OrderType")
                select item;
}

Get(int customerId, int versionId)
{
    // This was the method that was running
    var query = from item in context.Customers
                    .Include(item.Orders)
                select item;
}
Run Code Online (Sandbox Code Playgroud)

所以,这"Orders.OrderType"是正确的,虽然看起来很讨厌的解决方案.我需要一些咖啡因.

编辑:

回到这个问题,包含的最好方法是使用System.Data.Entity's Include方法:

.Include(x=> x.Orders.Select(o=> o.OrderType));
Run Code Online (Sandbox Code Playgroud)