gpt4 book ai didi

linq-to-entities - Entity Framework 代码优先 - 热切加载未按预期工作?

转载 作者:行者123 更新时间:2023-12-04 01:40:34 24 4
gpt4 key购买 nike

我有以下 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;}
}

问题是当我返回我的 ICollection<Order> 时我收到了 Order没问题,但是 OrderType Order 的属性(property)没有被填充。我的订单将包含以下详细信息:
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。

最佳答案

哦亲爱的。看来我是个十足的驴子。现在是 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的包含方法:
.Include(x=> x.Orders.Select(o=> o.OrderType));

关于linq-to-entities - Entity Framework 代码优先 - 热切加载未按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3780480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com