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

3
我有两个数据库实体需要使用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; }
}

无论我做怎样的配置,当我尝试像这样将一个账户实体实例插入到数据库时,总是会出现错误“无法确定依赖操作的有效顺序”。
var account = new Account();
var operation = new Operation();

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

dbContext.Accounts.Add(account);
dbContext.SaveChanges();
2个回答

3

幸运的是,EF推断出外键列AccountIdLastOperationId,所以这对我很有效:

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

2

这就是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; }
     }

账户表:列名:Id

操作表:列名:Id(与账户表共享),AccountForListId(1..n)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接