使用linq asp.net mvc选择多行并在表中编辑这些多行

时间:2015-12-04 09:39:22

标签: c# asp.net-mvc entity-framework linq asp.net-mvc-4

我有如下表格

enter image description here

我将Product_ID传递给" 01"我想将所有相关的行扩展到编辑器视图中,一旦我提交了那些将这些值保存到此表中。

对于GET方法,我需要选择相关的行并放置那些vaue intor编辑框

所以我创建了像这样的get方法

    [HttpGet]
    public ActionResult Product_Edit(string Product_ID)
    {
        Product_ID = "01";

        var product_fields = (from productstatistics in db.AB_Product_vs_Field
                              where productstatistics.Product_ID == Product_ID
                              select new AB_Product_vs_Field
                             {
                                Product_ID = productstatistics.Product_ID,
                                Field_ID = productstatistics.Field_ID,
                                Field_Value_EN = productstatistics.Field_Value_EN,
                                Field_Value_AR = productstatistics.Field_Value_AR
                             }).ToList();

        if (product_fields == null)
        {
            return HttpNotFound();
        }


        return View(product_fields);

    }

但是我在这里收到了异常消息

  

实体或复杂类型' project_name.table_name'不能在LINQ to Entities查询中构造。

编辑:这是view page

2 个答案:

答案 0 :(得分:2)

您应该选择product_fields,如下所示。

var product_fields = db.AB_Product_vs_Field.Where(p=>p.Product_ID==Product_ID);

由于它返回一个列表,你应该查看模型

@model List<project_name.Models.AB_Product_vs_Field>

在您的视图中使用foreach循环显示所有数据,如下所示。

@foreach (var item in Model)
{
    <div class="form-group">
        @Html.LabelFor(modelItem => item.Product_ID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(modelItem => item.Product_ID, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(modelItem => item.Product_ID, "", new {@class = "text-danger"})
        </div>
    </div>
    @*others information goes here*@
}

This dotnet小提琴可能对你有所帮助。 https://dotnetfiddle.net/XUJYAX

答案 1 :(得分:0)

尝试以下

[HttpGet]
public ActionResult Product_Edit(string Product_ID)
{
    Product_ID = "01";

    var product_fields = (from productstatistics in db.AB_Product_vs_Field
                          where productstatistics.Product_ID == Product_ID
                          select productstatistics).ToList();

    if (product_fields == null)
    {
        return HttpNotFound();
    }


    return View(product_fields);

}

您正在选择所有字段,因此您无需创建匿名对象。

相关问题