尝试绑定下拉列表时LINQ to Entities错误

时间:2011-02-10 21:23:48

标签: entity-framework asp.net-mvc-3

我正在尝试创建一个viewmodel并添加一个SelectListItem以允许我绑定下拉列表。 我有一个非常基本的viewmodel,看起来像这样

  public class CreatePurchaseViewModel
{
    public Product Product { get; set; }
    public IEnumerable<SelectListItem> Products { get; set; }
    public int SelectedProductId { get; set; }
    public DateTime OrderDate { get; set; }
    public bool OrderSent { get; set; }

}

我的控制器看起来像这样

 [HttpGet]
    public ActionResult Create()
    {
        var model = new CreatePurchaseViewModel
                        {
                            Products = context.Products.Select(x =>
                                                        new SelectListItem()
                                                            {
                                                                Text = x.ProductName,
                                                                Value = x.ProductID
                                                            })
                        };
       return View(model);
    }

然而,它抱怨Value = x.Product无法将int类型转换为string。因此,如果我添加.ToString,它编译好,但是当我尝试加载视图时出现错误

  

LINQ to Entities无法识别方法'System.String ToString()'方法,并且此方法无法转换为商店表达式。

我的观点

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>CreatePurchaseViewModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.SelectedProductId)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(x => x.SelectedProductId,Model.Products)
        @Html.ValidationMessageFor(model => model.SelectedProductId)
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.OrderDate)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model=>model.OrderDate)
        @Html.ValidationMessageFor(model => model.OrderDate)
    </div>
    <div>
    Sent
    @Html.RadioButtonFor(model => model.OrderSent, "Sent", new { @checked = true })
    Not Sent
    @Html.RadioButtonFor(model=>model.OrderSent,"Not Sent")

我对实体框架和mvc都很陌生,所以任何帮助都会很棒。

谢谢

1 个答案:

答案 0 :(得分:0)

您尚未指定产品模型的外观,但我们可以假设ProductID属性为整数,因此您可能需要将其转换为字符串:

[HttpGet]
public ActionResult Create()
{
    var model = new CreatePurchaseViewModel
    {
        Products = context.Products.Select(x =>
            new SelectListItem
            {
                Text = x.ProductName,
                Value = x.ProductID.ToString()
            }
        )
   };
   return View(model);
}