简体   繁体   中英

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM