2012-04-26 106 views
1

我有一個父子實體:外鍵實體框架問題

public class Transaction 
{ 
    public int TransactionId {get; set;} 
    public int? OrderId {get; set;} 
    public virtual Order Order {get; set;} 

} 

public class Order 
{ 
    public int Id {get; set;} 
    public virtual List<OrderItems> OrderItems {get; set;} 
} 

public class OrderItem 
{ 
    public int Id {get; set;} 
    public string Item {get; set;} 
    public virtual int OrderId {get; set;} 
    public virtual Order Order {get; set;} 
} 

的背景是如下:

modelBuilder.Entity<Transaction>() 
      .HasKey(x => x.TransactionId) 
      .ToTable("Transactions"); 

     modelBuilder.Entity<Transaction>() 
      .HasOptional(x => x.Order) 
      .WithMany() 
      .HasForeignKey(t => t.OrderId); 

     modelBuilder.Entity<Order>() 
      .HasKey(o => o.Id) 
      .ToTable("Orders"); 

     modelBuilder.Entity<OrderItem>() 
      .HasKey(i => i.Id) 
      .ToTable("OrderItems"); 


     modelBuilder.Entity<OrderItem>() 
      .HasRequired(x => x.Order) 
      .WithMany(o => o.OrderItems) 
      .HasForeignKey(p => p.OrderId); 

當我嘗試創建類型交易的一個新的實體,是這樣的:

var transaction = new Transaction 
        {TransactionId = Guid.NewGuid; 
        Order = new Order {OrderItems = new List<OrderItems>{Item="SunCream"}}}; 

ctx.Transactions.Add(transaction); 
ctx.SaveChanges(); 

我得到

INSERT語句衝突與外鍵約束 「FK_Transactions_Orders_OrderId」。衝突發生在數據庫 「Transactions」,表「dbo.Orders」,列'Id'。

我究竟在做什麼錯在這裏?

回答

1

我相信你需要在添加事務之前先將Order對象明確地添加到ctx對象中。通過這種方式,當您調用.SaveChanges()時,上下文將知道在提交事務之前必須首先提交訂單。

+0

你是對的。謝謝 – Elena 2012-04-26 13:49:45