11

我有以下实体框架 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;}
}

问题是,当我返回时,我ICollection<Order>得到了Orders 好的,但没有填充的OrderType属性。Order我的订单将包含以下详细信息:

Id:          1
CustomerId:  1
Customer:    Populated
OrderTypeId: 3
Type:        null        // Never returned

我的映射代码如下所示:

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

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

public Context(string connectionString)
    : base(connectionString)
{
    ObjectContext.ContextOptions.LazyLoadingEnabled = false;
}

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

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

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

1 -> .Include(x=> x.Orders.FirstOrDefault().OrderType)
2 -> .Include("Orders")
3 -> .Include("Orders")
     .Include("Orders.OrderType")

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

var query = from item in context.Orders
                .Include(x=> x.OrderType)
            select item;

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

4

1 回答 1

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;
}

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

编辑:

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

.Include(x=> x.Orders.Select(o=> o.OrderType));
于 2010-09-23T16:48:30.927 回答