Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To make this work, I had to add more fluent mappings, to explicitly create the optional mapping of the <code>TransferItem</code> on the <code>Transfer</code> class, as well as make the FK nullable on the <code>TransferItem</code>.</p> <p>I didn't have a problem wrapping this all in a single TransactionScope, once the mappings were fixed.</p> <p>Here's the entire console app:</p> <pre><code> public class Transfer { public long Id { get; set; } public long TransferIncomeItemId { get; set; } public long TransferExpenseItemId { get; set; } public TransferItem TransferIncomeItem { get; set; } public TransferItem TransferExpenseItem { get; set; } } public class Operation { public long Id { get; set; } public decimal Sum { get; set; } } public class TransferItem : Operation { public long? TransferId { get; set; } public Transfer Transfer { get; set; } } public class Model : DbContext { public DbSet&lt;Transfer&gt; Transfers { get; set; } public DbSet&lt;Operation&gt; Operations { get; set; } public DbSet&lt;TransferItem&gt; TransferItems { get; set; } protected override void OnModelCreating( DbModelBuilder modelBuilder ) { modelBuilder.Entity&lt;Transfer&gt;() .HasRequired( t =&gt; t.TransferIncomeItem ) .WithMany() .HasForeignKey( x =&gt; x.TransferIncomeItemId ) .WillCascadeOnDelete( false ); modelBuilder.Entity&lt;Transfer&gt;() .HasRequired( t =&gt; t.TransferExpenseItem ) .WithMany() .HasForeignKey( x =&gt; x.TransferExpenseItemId ) .WillCascadeOnDelete( false ); modelBuilder.Entity&lt;TransferItem&gt;() .HasOptional( t =&gt; t.Transfer ) .WithMany() .HasForeignKey( ti =&gt; ti.TransferId ); } } class Program { static void Main( string[] args ) { using( var scope = new TransactionScope() ) { var context = new Model(); var ti1 = new TransferItem(); var ti2 = new TransferItem(); //deal with the types with nullable FKs first context.Operations.Add( ti1 ); context.Operations.Add( ti2 ); var t = new Transfer(); context.Transfers.Add( t ); t.TransferIncomeItem = ti1; t.TransferExpenseItem = ti2; //save, so all objects get assigned their Ids context.SaveChanges(); //set up the "optional" half of the relationship ti1.Transfer = t; ti2.Transfer = t; context.SaveChanges(); scope.Complete(); } } } </code></pre> <p>When ran produced this database:</p> <p><img src="https://i.stack.imgur.com/HDJR7.png" alt="enter image description here"></p> <p>And this output:</p> <p><img src="https://i.stack.imgur.com/T0OxF.png" alt="enter image description here"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload