使用 Fluent api,如何将自定义类型映射为 DbContext 类的 OnModelCreating 方法中的主键?
我正在尝试使用 EF Core 为以下实体构建模型。
public class Account
{
public AccountId AccountId { get; }
public string Name { get; set; }
private Account()
{
}
public Account(AccountId accountId, string name)
{
AccountId = accountId;
Name = name;
}
}
主键是AccountId
;该类型是一个像这样的简单值对象。
public class AccountId
{
public string Id { get; }
public AccountId(string accountId)
{
Id = accountId;
}
}
Within OnModelCreating
,我发现我无法映射AccountId
没有支持场。所以我引入了backing field_accountId
。我不希望 AccountId 有设置器。
public class Account
{
private string _accountId;
public AccountId AccountId { get { return new AccountId(_accountId); } }
public string Name { get; set; }
private Account()
{
}
public Account(AccountId accountId, string name)
{
_accountId = accountId.Id;
Name = name;
}
}
但我仍然无法弄清楚如何指定具有支持字段的属性,该支持字段也是主键。
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var account = modelBuilder.Entity<Account>();
account.ToTable("Accounts");
account.HasKey(x => x.AccountId);
account.Property(x => x.AccountId).HasField("_accountId");
}
OnModelCreating 在属性映射行上引发异常 (account.Property(x => x.AccountId).HasField("_accountId");
)。
声明属性和字段必须是同一类型。