Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF6: Configure complex mapping for entities (code first)

I've got two db entities I want to configure using EF6 fluent API.

public class Account
{
    public Int32 Id { get; set; }

    public Int32? LastOperationId { get; set; }
    public virtual Operation LastOperation { get; set; }

    public virtual List<Operation> Operations { get; set; }
}

public class Operation
{
    public Int32 Id { get; set; }

    public Int32? AccountId { get; set; }
    public virtual Account Account { get; set; }
}

For any configuration I always get an error "Unable to determine a valid ordering for dependent operations" when trying to insert an account entity instance into a db like this:

var account = new Account();
var operation = new Operation();

account.Operations = new List<Operation>() { operation };
account.LastOperation = operation;

dbContext.Accounts.Add(account);
dbContext.SaveChanges();
like image 533
shadeglare Avatar asked Dec 02 '25 09:12

shadeglare


2 Answers

Fortunately, EF infers foreign key columns AccountId and LastOperationId, so this works for me:

modelBuilder.Entity<Operation>()
.HasKey(x => x.Id)
.HasOptional(x => x.Account)
.WithMany(x => x.Operations);

modelBuilder.Entity<Account>()
.HasKey(x => x.Id)
.HasOptional(x => x.LastOperation);
like image 76
stop-cran Avatar answered Dec 04 '25 00:12

stop-cran


this is the combination excatly what you need in Code-First:

public class Account
{
    // One to one to one relationship (shared PK)
     public int Id { get; set; }

     // One to one to one relationship (shared PK)
     public virtual Operation Operation { get; set; }

    // One to many relationship foreign Key
    [InverseProperty("AccountForList")]
     public virtual List<Operation> Operations { get; set; }
   }

   public class Operation
   {
    // One to one to one relationship (shared PK)
    [ForeignKey("Account")]
     public Int32 Id { get; set; }

     // One to one to one relationship (shared PK)
     public virtual Account Account { get; set; }

     // One to many relationship foreign Key
     public Int32? AccountForListId { get; set; }

     // One to many relationship foreign Key
     [ForeignKey("AccountForListId")]
     public virtual Account AccountForList { get; set; }
     }

Account Table: columnname : Id

Operation Table: column name Id(shared with Account), AccountForListId (1..n)

like image 40
Bassam Alugili Avatar answered Dec 04 '25 00:12

Bassam Alugili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!