I have one parent child entity :
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;}
}
the context is as following :
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 );
When I try to create a new entity of type Transaction, something like :
var transaction = new Transaction
{TransactionId = Guid.NewGuid;
Order = new Order {OrderItems = new List<OrderItems>{Item="SunCream"}}};
and
ctx.Transactions.Add(transaction);
ctx.SaveChanges();
I get
The INSERT statement conflicted with the FOREIGN KEY constraint
“FK_Transactions_Orders_OrderId”. The conflict occurred in database
“Transactions”, table “dbo.Orders”, column ‘Id’.
What exactly am I doing wrong here ?
I believe that you need to explicitly add the Order object to the ctx object first before you add the transaction. That way when you call the
.SaveChanges()the context will know it has to commit the Order first before you commit the Transaction.