Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ObjectContext实例已被释放-Winforms实体框架_C#_Winforms_Entity Framework - Fatal编程技术网

C# ObjectContext实例已被释放-Winforms实体框架

C# ObjectContext实例已被释放-Winforms实体框架,c#,winforms,entity-framework,C#,Winforms,Entity Framework,我正在尝试解决此问题,并阅读了有关此错误的内容,但无法找到解决方案。 我正在为一个简单的产品类别场景使用实体框架构建一个winforms应用程序。 这是我的模型的快照。 ProductService类中检索所有产品的代码为 public static List<Product> GetAllProducts() { List<Product> products = new List<Product>(); using (var entity

我正在尝试解决此问题,并阅读了有关此错误的内容,但无法找到解决方案。 我正在为一个简单的产品类别场景使用实体框架构建一个winforms应用程序。 这是我的模型的快照。

ProductService类中检索所有产品的代码为

public static List<Product> GetAllProducts()
{
    List<Product> products = new List<Product>();
    using (var entity = new SUIMSEntities1())
    {
        products = (from p in entity.Products
                    select p).ToList();
        return products;
    }            
}
公共静态列表GetAllProducts() { 列表产品=新列表(); 使用(var entity=new suimEntities1()) { 产品=(来自实体产品中的p 选择p.ToList(); 退货产品; } } 产品代码中的代码隐藏为

List<Product> prods=ProductServices.GetAllProducts();
dgvProducts.DataSource = prods;
List prods=ProductServices.GetAllProducts();
dgvProducts.DataSource=prods;
当我尝试在datagridview中加载产品时,显示以下错误:

你能告诉我是什么引起了这个问题吗

编辑: Include完成了这个技巧,在这个特定场景中,我更改了GetAllProducts(),如下所示

公共静态列表GetAllProducts() { 使用(var entity=new suimEntities1()) { 列表产品=实体.products.Include(“类别”).ToList(); 退货产品; } }
尽管您返回了一个
列表
,但访问该类别似乎会导致数据库访问。问题是您已经处理了访问数据库所需的上下文。

默认情况下,实体框架(EF)将延迟加载您的类别对象集。因为您的类别对象集是延迟加载的,所以当其他代码稍后引用类别时,EF将尝试加载该集。但是,此时,您的上下文已被处理,导致您看到的错误

您需要做的是强制上下文急切地加载您的类别实体集,如下所示:

public static List<Product> GetAllProducts()
{
    List<Product> products = new List<Product>();
    using (var entity = new SUIMSEntities1())
    {
        entity.Include("Category");  //force eager loading of Category
        products = (from p in entity.Products
                    select p).ToList();
        return products;
    }            
}
公共静态列表GetAllProducts() { 列表产品=新列表(); 使用(var entity=new suimEntities1()) { entity.Include(“Category”);//强制加载类别 产品=(来自实体产品中的p 选择p.ToList(); 退货产品; } }
在中,因此通常将代码和错误消息作为文本发布,而不是文本的屏幕抓图。您能否编辑您的答案以显示您所描述的内容?准确地显示一个人将在哪里使用.Include。我已经在我的答案中添加了一些澄清。
public static List<Product> GetAllProducts()
{
    List<Product> products = new List<Product>();
    using (var entity = new SUIMSEntities1())
    {
        entity.Include("Category");  //force eager loading of Category
        products = (from p in entity.Products
                    select p).ToList();
        return products;
    }            
}