带有EntityFramework的MVC中的Html.RenderAction

时间:2012-03-17 23:53:37

标签: asp.net-mvc entity-framework-4 dbcontext renderaction

我的问题是当我尝试使用两个Html.RenderAction渲染视图时。它说:“操作无法完成,因为已经处理了DbContext”。

我以这种方式配置了Ninject:

Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope;

但如果我以默认方式做...

Bind<IUnitOfWork>().To<UnitOfWork>()

没有错误。

我必须在RequestScope中使用它(所以我认为),但我该怎么做呢?看来,当第二个Html.RenderAction被调用时,之前的DbContext被处理了!

更新:

这是主要观点(为简洁起见)

@model FoodAway.Model.Product
@Html.ValidationSummary(true) 
<fieldset>
    <legend>Producto</legend>
    @using (Html.BeginForm())
    {
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        @Html.HiddenFor(model => model.Id)
        <p>
            <input type="submit" value="Guardar" />
        </p>
    }
    <fieldset>
        <div class="editor-label">
            @Html.LabelFor(model => model.Ingredients)
        </div>
        <div class="editor-field">
            @{Html.RenderAction("IngredientsToRemoveList", "Ingredients");}
        </div>
    </fieldset>
    <fieldset>
        @{Html.RenderAction("IngredientsToAddList", "Ingredients");}
    </fieldset>
</fieldset>

和他的控制者/行动:

    public ActionResult EditProduct(string name)
    {
        Product product = unitOfWork.ProductRepository.Get(i => i.Name ==name).FirstOrDefault();
        if (product == null)
            return HttpNotFound();
        return View(product);
    }

所以,DBContext中的错误是当我有这2个RenderAction方法时,奇怪的是如果我只有1个RenderAction则没有问题!!!!!

1 个答案:

答案 0 :(得分:0)

在将集合传递给视图之前,您需要枚举该集合。这意味着您在DbContext的有效范围内查询数据库。

您可以在控制器中使用.ToArray()来执行此操作

相关问题