2014-12-01 211 views
1

如何正確保存到數據庫?我有以下但不工作。我正在使用自定義ModelMetadataORDERMetadata)並將其設置爲等於.edmx/order.cs模型並嘗試保存它。MVC保存到數據庫

Order.cs模型的關鍵字段是[OrderID],但我通過了[model.Order_Number]這是唯一的值。我目前沒有通過[OrderID]ORDERMetadata模式。這是必需的嗎?

Order.cs

public partial class ORDER 
{ 
    public int OrderID { get; set; } 
    public int Order_Number { get; set; } 
    public string Order_Type { get; set; } 
} 

ORDERMetadata模型:

[MetadataType(typeof(ORDERMetadata))] 
public partial class ORDER 
{ 
    // Blank. It's just here to add the class-level attribute. 
} 

public class ORDERMetadata 
{ 
    [Display(Name = "Order Number")] 
    public int Order_Number { get; set; } 
    [Display(Name = "Order Type")] 
    public string Order_Type { get; set; } 
} 

控制器:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Edit(ORDERMetadata model) 
{ 
    if (!ModelState.IsValid) 
    { 
     return View(model); 
    } 

    try 
    { 
     // update order 
     ORDER order = new ORDER(); 
     order.Order_Number = model.Order_Number; 

     order.Order_Type = model.Order_Type; 

     db.Entry(order).State = EntityState.Modified; 
     db.SaveChanges(); 

     ViewBag.UpdateResult = "Order updated!"; 
     return View(); 
    } 
} 
+3

更新時應該使用現有實體,但是要創建一個新實體 – 2014-12-01 21:30:19

回答

0

更改爲:

ORDER順序= db.ORDERS.SingleOrDefault( p => p.Order_Number == model.Order_Number);