简体   繁体   English

EF6:为实体配置复杂映射(代码优先)

[英]EF6: Configure complex mapping for entities (code first)

I've got two db entities I want to configure using EF6 fluent API. 我有两个db实体,我想使用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: 幸运的是,EF推断外键列AccountIdLastOperationId ,所以这对我LastOperationId

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: 这是您在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 帐户表:columnname:Id

Operation Table: column name Id(shared with Account), AccountForListId (1..n) 操作表:列名Id(与Account共享),AccountForListId(1..n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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