2011-02-10 91 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