[英]Last inserted id with EF 4.1 , MVC 3
我正在使用asp.net mvc 3和EF 4.1與visual studio 2010並且我是新手。
我有一個關於最后插入的ID的問題。 我的數據庫中有兩個表“points_Order”和“points_OrderDetails”。
db.Order.Add(po);
db.SaveChanges();
//second thing i have tried
var orderID = (from oi in db.Order
select oi.ID)
.Max(i => i);
// and this first thing
pod.OrderID = po.ID;
pod.OrderID = orderID;
db.OrderDetails.Add(pod);
db.SaveChanges();
上下文類:
public class points_Order {
[Key]
public int ID { get; set; }
public string Owner { get; set; }
public DateTime Date { get; set; }
public byte Status { get; set; }
public int Total { get; set; }
//public virtual points_OrderDetails OrderDetail { get; set; }
}
public class points_OrderDetails {
[Key]
public int OrderID { get; set; }
public string OrderType { get; set; }
public int Amount { get; set; }
public int ItemID { get; set; }
public int ItemRecord { get; set; }
public string ItemCode { get; set; }
public byte Plus { get; set; }
public byte Degree { get; set; }
public string Kind { get; set; }
public string Sex { get; set; }
public string Race { get; set; }
public string Tier { get; set; }
public string SetItem { get; set; }
public string SOX { get; set; }
//public Blues Blue { get; set; }
}
public DbSet<points_Order> Order { get; set; }
public DbSet<points_OrderDetails> OrderDetails { get; set; }
我得到錯誤“{”無法將值NULL插入列'OrderID',表'db.dbo.points_OrderDetails'; 列不允許空值。 INSERT失敗。\\ r \\ n語句已終止。“}”
我能做什么? 難道我做錯了什么?
如果您從模型中的訂單 - >訂單詳細信息定義關系,它應該像這樣工作:
po.Details.Add(pod); // or pod.Order = po;
db.Order.Add(po);
db.SaveChanges();
EF應該為你找出關系,不需要手動設置ID。
更新:你正在嘗試做一些不受支持的事情。 你有一對一的映射; EF不支持您想要的方式(共享主鍵)。 見http://weblogs.asp.net/manavi/archive/2011/05/01/associations-in-ef-4-1-code-first-part-5-one-to-one-foreign-key-associations .aspx有關如何在EF中進行一對一模型的說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.