shadeglare
shadeglare

Reputation: 7536

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();

Upvotes: 3

Views: 461

Answers (2)

Bassam Alugili
Bassam Alugili

Reputation: 17033

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)

Upvotes: 2

stop-cran
stop-cran

Reputation: 4408

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);

Upvotes: 3

Related Questions