gpt4 book ai didi

c# - EF6 : Configure complex mapping for entities (code first)

转载 作者:行者123 更新时间:2023-11-30 14:50:00 30 4
gpt4 key购买 nike

我有两个要使用 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();

最佳答案

幸运的是,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);

关于c# - EF6 : Configure complex mapping for entities (code first),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37863482/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com