我上课
public void Configure(EntityTypeBuilder<Document> builder)
{
builder.ToTable("Document");
builder.HasKey(x => x.TranId);
builder.OwnsOne(a => a.Record, a =>
{
a.ToTable("Doc_Record");
a.Property(p => p.TranId).HasMaxLength(100)
.HasColumnName("TranID")
.HasDefaultValue("");
a.OwnsMany(x => x.DataResults, x =>
{
x.ToTable("Doc_Rec_DataResults");
x.Property(p => p.DataSourceName).HasMaxLength(150)
.HasColumnName("DataSourceName")
.HasDefaultValue("");
});
}
}
我想将Record和DataResult类映射为Value对象,所以我尝试将其映射为
a.OwnsMany(x => x.DataResults, x =>
{
x.WithOwner().HasForeignKey("RecordId");
x.ToTable("Doc_Rec_DataResults");
x.Property(p => p.DataSourceName).HasMaxLength(150)
.HasColumnName("DataSourceName")
.HasDefaultValue("");
});
当我尝试添加此迁移时,出现错误消息:
实体类型“ DataResult”需要定义主键。
有人建议使用this link,我尝试添加
WithOwner
但是这种方法不起作用,因为我正在使用.net core 3
的{{1}}可以使用.net core 2
(我真的需要将RecordId
属性添加到{{ 1}}类(它是一个值对象)。
如果有人可以提供一个示例,说明如何使用Record
中的OwnsMany
映射值对象的集合,那就太好了。
答案 0 :(得分:0)
在这个ef核心2.2 example中,我们有一个Company
,它拥有Addresses
的集合,这是实现。请注意,我省略了一些有用的代码来说明这一点,请参阅完整示例以获取进一步说明。另请注意,此功能OwnsMany()
在pre ef core 2.2中不可用
public class CompanyAddress
{
public string City { get; }
public string AddressLine1 { get; }
}
public class Company
{
private List<CompanyAddress> addresses = new List<CompanyAddress>();
public Guid Id { get; }
public string Name { get; }
public IEnumerable<CompanyAddress> Addresses { get => this.addresses; }
public void AssignAddress(CompanyAddress address)
{
var exists = this.addresses.Contains(address);
if (!exists)
{
this.addresses.Add(address);
}
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Company>().OwnsMany<CompanyAddress>("Addresses", a =>
{
a.HasForeignKey("CompanyId");
a.Property(ca => ca.City);
a.Property(ca => ca.AddressLine1);
a.HasKey("CompanyId", "City", "AddressLine1");
});
}
here's a repo为文章所有者提供完整解决方案