之前用的是 .net core 2.2 ,一对一映射关系是这么配置的
builder.OwnsOne(post => post.ViewCount).HasForeignKey(vc => vc.EntryId);
升级至 .net core 3.0 之后,不支持 OwnsOne 之后直接跟 HasForeignKey ,必须要加 WithOwner ,于是改为:
builder.OwnsOne(post => post.ViewCount).WithOwner().HasForeignKey(vc => vc.EntryId);
但运行报错
The type 'ViewCount' cannot be configured as non-owned because an owned entity type with the same name already exists
请问如何解决这个问题?
问题是 modelBuilder.Entity<ViewCount>().HasKey(v => v.EntryID)
与 builder.OwnsOne(post => post.ViewCount).WithOwner().HasForeignKey(vc => vc.EntryId)
配置冲突引起的,被 own 的实体配置都要放在 OwnsOne 中,正确的配置方法如下:
builder.OwnsOne(post => post.ViewCount, vc =>
{
vc.HasKey(v => v.EntryID);
vc.WithOwner().HasForeignKey(_ => _.EntryID);
});