1
如何正確保存到數據庫?我有以下但不工作。我正在使用自定義ModelMetadata
(ORDERMetadata
)並將其設置爲等於.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();
}
}
更新時應該使用現有實體,但是要創建一個新實體 – 2014-12-01 21:30:19