次のEntityFrameworkPOCOクラスがあります。
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
大丈夫ですが、の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")
ただし、Orderを直接ロードしない限り、OrderTypeプロパティが返されることはありません。
var query = from item in context.Orders
.Include(x=> x.OrderType)
select item;
このコードは、注文内のOrderTypeを正しく返します。