MVC 3 - ObjectContext中的实例已被处置,不能再用于需要连接的操作 [英] MVC 3 - The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

查看:1179
本文介绍了MVC 3 - ObjectContext中的实例已被处置,不能再用于需要连接的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是很新的,一般C#和MVC和我一直在创造我自己的小博客网站作为一个测试项目。虽然大多数东西都工作到这一点,我不得不从LINQ查询中选择多个列的问题。它仅磕磕绊绊上让我意识到我可以使用生成的实体类的强类型模型来处理这个问题后。我需要这个,因为我一直在创建数据库层(这也是我的东西还没有使用过),并试图通过匿名类型通过层没有工作。我理解为什么是这样的话,让我很满意,我在正确的方向也得走。

I'm very new to C# and MVC in general and I've been creating my own little blog site as a test project. Although most things are working up to this point, I have had problems selecting multiple columns from LINQ queries. It was only after stumbling on a question on SO that I realised I could use the generated entities classes as strongly-typed models to handle this. I've needed this as I've been creating a database layer (which is also something I've not used before) and trying to pass anonymous types through that layer didn't work. I understand why that was the case, so I'm satisfied that I'm heading in the right direction.

不过,这种做法似乎已经给了我另一个问题。我已经尝试了简单的测试来检索我的分类表2列:类别ID和姓名。我最初尝试以下操作:

However, this approach seems to have given me another problem. I've tried a simple test to retrieve 2 columns from my Categories table: CategoryID and Name. I initially tried the following:

using (MyEntities db = new MyEntities())
{
    var model = from c in db.Categories
                select new Category { CategoryID = c.CategoryID, Name = c.Name };

    return View(model);
}

这给了我试图遍历视图模型时ObjectContext中配置错误。阅读这个问题之后,我试着动return语句的使用块外和像这样的模型调用AsEnumerable():

This gave me the ObjectContext is disposed error when trying to iterate over the model in the view. After reading this question, I tried moving the return statement outside of the using block and calling AsEnumerable() on the model like so:

IEnumerable<Category> model;

using (MyEntities db = new MyEntities())
{
    model = from c in db.Categories
            select new Category { CategoryID = c.CategoryID, Name = c.Name };
}

return View(model.AsEnumerable());

不过,这仍然给我相同的ObjectContext配置错误,当我尝试遍历视图模型。所以现在我不明白,为什么我得到的错误。我甚至试过完全删除using指令,但是这给了我一个不同的错误:

However, this is still giving me the same ObjectContext is disposed error when I try to iterate over the model in the view. So now I don't understand why I'm getting the error. I've even tried removing the using directive completely but that gives me a different error:

的实体或复杂类型'MyProjectModel.Category'不能在一个LINQ被构造为实体的查询。

"The entity or complex type 'MyProjectModel.Category' cannot be constructed in a LINQ to Entities query."

如果有帮助,这里的相关code对我的看法:

If it helps, here's the relevant code for my view:

@model IEnumerable<MyProject.Models.Category>

@foreach (var category in Model)
{
    <p>@category.Name</p>
}

会有人好心地开导我,以我缺少的是什么?

Would someone be kind enough to enlighten me as to what I'm missing?

感谢。

推荐答案

在控制器渴望并呼吁 .ToList()以调度执行前处理你已经离开了使用块(如后为时已晚,上下文就没了)之前及时查询:

Be eager in the controller and call .ToList() before disposing in order to schedule the execution of the query immediately before you have left the using block (as after that it is too late, the context is gone):

using (MyEntities db = new MyEntities())
{
    var model = 
        from c in db.Categories
        select new Category 
        { 
            CategoryID = c.CategoryID, 
            Name = c.Name 
        };
    return View(model.ToList()); // <-- .ToList() here
}

现在,虽然这将解决您的具体问题,哪些开发商或依赖注入框架通常做的是实例化的DbContext 中的的BeginRequest 事件,它里面存储了 HttpContext.Items ,以便它可以在整个请求的执行,并在 EndRequest 方法,从的HttpContext 和处置它。

Now, while this will solve your particular problem, what developers or dependency injection frameworks usually do is to instantiate the DbContext inside the BeginRequest event, store it inside the HttpContext.Items so that it is available throughout the execution of the entire request and inside the EndRequest method, retrieve it from HttpContext and dispose it.

更新:

此外,它是使用只包含的属性视图模型,你想在这个特殊的视图中使用一个很好的做法:

Also it is a good practice to use a view model containing only the properties you would like to use in this particular view:

public class CategoryViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

,然后你的行动里:

and then inside your action:

public ActionResult Index()
{
    using (MyEntities db = new MyEntities())
    {
        var model = 
            from c in db.Categories
            select new CategoryViewModel
            { 
                Id = c.CategoryID, 
                Name = c.Name 
            };
        return View(model.ToList());
    }
}

和视图:

@model IEnumerable<MyProject.Models.CategoryViewModel>

@foreach (var category in Model)
{
    <p>
        Id: @category.Id 
        Name: @category.Name
    </p>
}

这篇关于MVC 3 - ObjectContext中的实例已被处置,不能再用于需要连接的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆