简体   繁体   English

MVC和Entity Framework中的MM关系仅在调试器模式下有效

[英]M-M relationship in MVC and Entity Framework works only in debugger mode

I am doing some project for school and have encountered a strange thing. 我正在为学校做一些项目,遇到了一件奇怪的事情。 Situation is like this: 情况是这样的:

In my SQL Server db I have 3 tables: Product, Ingredient and ProductIngredient. 在我的SQL Server数据库中,我有3个表:Product,成分和ProductIngredient。 The last one is PJT between the first two. 最后一个是前两个之间的PJT。

I have this in a controller: 我在控制器中有这个:

public ActionResult Index()
        {
            List<Product> products;
            using (FastfoodConnection conn = new FastfoodConnection())
            {
                products = conn.Products.ToList();

            }
            TestModel tM = new TestModel();
            tM.Products = products;
            return View(tM);
        }

and here is my view: 这是我的看法:

@foreach (var product in Model.Products)
{
    <tr>
        <td> @product.Name</td>
        <td> @product.Description</td>

    </tr>
    <tr>
        <th>Ingredients</th>
    <tr>
    <tr>
      <td>
        <ul>
           @foreach (var ingredient in product.Ingredients)
           {
            <li>@ingredient.IngredientName</li>
           }
        </ul>
      </td>
    </tr>
}
</table>

Now - when I set the breakpoint in controller and debug the code, step by step, everything works fine and result shows as I want it to. 现在-当我在控制器中设置断点并逐步调试代码时,一切正常,结果如我所愿。 However, when I try to run the code (without debugging) I get ObjectDisposedException with description "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection." 但是,当我尝试运行代码(不进行调试)时,得到ObjectDisposedException,其描述为“ ObjectContext实例已被处置,不能再用于需要连接的操作。” Apparently this regards to product.Ingredients list which is null. 显然,这与product.Ingredients列表有关。

My question is: What could be the problem and how can it be solved? 我的问题是:可能是什么问题,如何解决?

You need to eager load the Ingredients . 您需要渴望加载Ingredients EF won't try to fetch those from the database until you need them, which is called Lazy Loading. 直到您需要它们,EF才会尝试从数据库中获取它们,这称为延迟加载。 Because you try to access them after you disposed your context, EF can't query the database for the Ingredients and you get an exception. 因为您在处置上下文之后尝试访问它们,所以EF无法在数据库中查询“ Ingredients ,因此您将获得异常。 Eager loading tells EF it should also fetch those entities in the same run when it gets the Products. 急切的加载告诉EF,当获得产品时,它也应该在同一运行中获取这些实体。 It's always a good idea to use eager loading when you know beforehand you will need the entities. 事先知道需要实体时,使用预先加载总是一个好主意。 This avoids multiple db calls since everything gets fetched in one query. 这避免了多次数据库调用,因为所有内容都在一个查询中获取。 It can be invoked through the Include(...) method: 可以通过Include(...)方法调用它:

public ActionResult Index()
    {
        List<Product> products;
        using (FastfoodConnection conn = new FastfoodConnection())
        {
            products = conn.Products.Include(p => p.Ingredients).ToList();

        }
        TestModel tM = new TestModel();
        tM.Products = products;
        return View(tM);
    }

This should resolve your problem. 这应该可以解决您的问题。 Also make sure you have the collection of Ingredients marked as virtual in your product model, which enables lazy/eager loading, but since it works in debugging mode I guess that will be alright. 还要确保您在产品模型中将Ingredients的集合标记为virtual ,这样可以实现延迟/急切加载,但是由于它可以在调试模式下运行,所以我想这会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架6查询性能(MM关系) - Entity Framework 6 Query Performance (M-M Relationship) 实体框架,M:M关系,无需引用完整性 - Entity Framework, M:M relationship WITHOUT referential Integrity 实体框架M:1关系导致主键重复 - Entity Framework M:1 relationship resulting in primay key duplication 存储m:n关系时的实体框架DbUpdateException - Entity Framework DbUpdateException when storing m:n relationship 在M:M关系中映射弱实体 - Mapping a weak entity in M:M Relationship 实体框架和与MVC的关系 - Entity Framework and the relationship with MVC 与Entity Framework 5和.net MVC 4的关系 - relationship with Entity Framework 5 and .net MVC 4 .Net 5 Entity Framework 从涉及 FK 1:M 关系的查询中删除不必要的调用 - .Net 5 Entity Framework removing unneccessary calls from Query involving FK 1:M relationship 实体框架 - “两个对象之间的关系无法定义”错误,但我认为我使用的是相同的上下文 - Entity Framework - “The relationship between the two objects cannot be defined” error, but I think I'm using the same context 在 Entity Framework Core/LINQ 中对 1:M:M:1 相关数据进行分组和扁平化 - grouping and flatening 1:M:M:1 related data in Entity Framework Core/LINQ
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM