刷新 EF 6 DBContext
Refresh EF 6 DBContext
我正在使用 Entity Framework 6,我有一个产品对象,其中包含如下变体列表:
public class Product
{
public int ProductId { get; set;}
public virtual ICollection<Variant> Variants { get; set;}
... other properties
}
public class Variant
{
public int VariantId { get; set;}
public int ProductId { get; set;}
public virtual Product Product { get; set;}
public int StoreId { get; set;}
... other properties
}
我用它从上下文中获取产品:
public static GetProducts()
{
using (MyDBContext context = new MyDBContext())
{
return context.Products.Include(p => p.Variants);
}
}
现在一切正常,当我收到 Product
时,它会返回变体。然而,今天早上我愚蠢地使用上下文中的 Product
而不是 DTO 并根据 StoreId
过滤变体,现在每当我得到 Product
时,它只会 returns 该商店的变体(即使我从未提交任何更改)。
我已经检查了数据库,所有变体仍然存在,那么如何重置我的上下文以便再次获取所有变体。
我试过以下方法:
- 正在重置 iis
- 清理并重建解决方案
- 将对象更改为 return 一个额外的 属性
重新加载产品使用:
foreach (Product product in context.Products)
{
context.Entry(product).Reload();
}
但似乎没有任何效果,我还需要做些什么来重置上下文吗?
事实证明这是变体实体而不是过滤上下文的配置错误。我只将 VariantID
用作 Key
但由于有多个具有相同 ID 的变体,因此在映射查询后返回的对象(让它看起来好像只有我过滤的商店)。
我通过使密钥对商店和变体 ID 唯一来解决此问题:
HasKey(v => new {v.VariantId, c.StoreId});
我正在使用 Entity Framework 6,我有一个产品对象,其中包含如下变体列表:
public class Product
{
public int ProductId { get; set;}
public virtual ICollection<Variant> Variants { get; set;}
... other properties
}
public class Variant
{
public int VariantId { get; set;}
public int ProductId { get; set;}
public virtual Product Product { get; set;}
public int StoreId { get; set;}
... other properties
}
我用它从上下文中获取产品:
public static GetProducts()
{
using (MyDBContext context = new MyDBContext())
{
return context.Products.Include(p => p.Variants);
}
}
现在一切正常,当我收到 Product
时,它会返回变体。然而,今天早上我愚蠢地使用上下文中的 Product
而不是 DTO 并根据 StoreId
过滤变体,现在每当我得到 Product
时,它只会 returns 该商店的变体(即使我从未提交任何更改)。
我已经检查了数据库,所有变体仍然存在,那么如何重置我的上下文以便再次获取所有变体。
我试过以下方法:
- 正在重置 iis
- 清理并重建解决方案
- 将对象更改为 return 一个额外的 属性
重新加载产品使用:
foreach (Product product in context.Products) { context.Entry(product).Reload(); }
但似乎没有任何效果,我还需要做些什么来重置上下文吗?
事实证明这是变体实体而不是过滤上下文的配置错误。我只将 VariantID
用作 Key
但由于有多个具有相同 ID 的变体,因此在映射查询后返回的对象(让它看起来好像只有我过滤的商店)。
我通过使密钥对商店和变体 ID 唯一来解决此问题:
HasKey(v => new {v.VariantId, c.StoreId});