使用DbContext和模型返回视图的问题 [英] issue with using DbContext and returning view with the model

查看:132
本文介绍了使用DbContext和模型返回视图的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 ModelState 无效,我需要从数据库中获取某些内容,并与模型一起返回,但是我似乎无法使用 using ,我想

I need to fetch something from the database and return that with the model if ModelState is not valid, however I seem to not be able to use using and I want to.

因此此代码有效:

[HttpPost]
        public ActionResult EditProduct(ProductVM productVM, HttpPostedFileBase file)
        {
            // Check model state
            if (!ModelState.IsValid)
            {
                Db db = new Db();
                productVM.Categories = new SelectList(db.Categories, "Id", "Name");

                return View(productVM);

            }

            return View(productVM);
        }

此代码引发以下错误:

The operation cannot be completed because the DbContext has been disposed.

[HttpPost]
public ActionResult EditProduct(ProductVM productVM, HttpPostedFileBase file)
{
    // Check model state
    if (!ModelState.IsValid)
    {
        using (Db db = new Db())
        {
            //Db db = new Db();
            productVM.Categories = new SelectList(db.Categories, "Id", "Name");
        }

        return View(productVM);

    }

    return View(productVM);
}

我可以以某种方式使用 using 仍然可以正常工作吗?

Can I somehow use using and still have it work?

推荐答案

正如@Stephen Muecke所说,您必须使用 ToList() AsEnumerable()来实现该集合.如果您不扩大集合的范围,它将不会立即运行.这就是为什么您会收到该错误.应该是这样

As @Stephen Muecke said you must materialize the collection using ToList() or AsEnumerable(). If you don't enumarate the collection, it won't run immediately. That's why you are getting that error. So it should be;

productVM.Categories = new SelectList(db.Categories.ToList(), "Id", "Name");

希望有帮助,

这篇关于使用DbContext和模型返回视图的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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