我有以下实体框架 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>
得到了Order
s 好的,但没有填充的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。