2011-02-10 96 views
0

我想创建一个viewmodel并添加一个SelectListItem来允许我绑定下拉列表。 我有一个看起来像这样尝试绑定下拉列表时出现LINQ to Entities错误

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); 
    } 

然而,抱怨值= x.Product不能int类型转换为字符串一个很基本的视图模型。所以,如果我添加的ToString它编译好的,但是当我尝试加载视图我得到一个错误

LINQ到实体无法识别方法“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") 

Im相当新实体完整性框架和MVC所以任何帮助将是巨大的。

谢谢

回答

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); 
} 
+0

喜Darin 我尝试过,但是我仍然收到错误 > LINQ to Entities无法识别方法'System.String ToString()'方法,并且此方法无法转换为存储表达式。 – 2011-02-10 21:33:00