我正在尝试为连接表 OwnerCows.dbo 理顺 EF 模型。有一个带有 Id 的类 Cow,一个带有 Id 的类 Owner,我想在只有 OwnerCowId、CowId(FK) 和 OwnerId(FK) 的 OwnerCows 表中引用它们。
我得到的错误是:无法在'Owner.OwnerCows'和'OwnerCow.Owner'之间创建关系,因为'Owner.CowOwners'和'OwnerCow.Owner'之间已经存在关系。导航属性只能参与单个关系。
这是否意味着我有一个循环引用?我该如何解决这个问题?
所有者.cs:
public class Owner : EntityBase<Guid>
{
public string Name { get; set; }
[NotMapped]
public ICollection<Cow> Cows { get; set; }
= new List<Cow>();
public virtual List<OwnerCow> CowOwners { get; set; }
public Cow Cow { get; set; }
}
牛.cs:
public class Cow : EntityBase<Guid>
{
[MaxLength(50)]
public string Name { get; set; }
public string Breed { get; set; }
public string Color { get; set; }
public ICollection<Entities.Weight> Weights { get; set; }
= new List<Weight>();
public ICollection<Vaccination> Vaccinations { get; set; }
= new List<Vaccination>();
[NotMapped]
public ICollection<Owner> CowOwners { get; set; }
= new List<Owner>();
public List<OwnerCow> OwnerCows { get; set; }
}
OwnerCows.cs:
public class OwnerCow
{
public Guid OwnerCowId { get; set; }
public Cow Cow { get; set; }
public Guid CowId { get; set; }
public Owner Owner { get; set; }
public Guid OwnerId { get; set; }
}
上下文类:
public class DogFaceContext : DbContext
{
public DogFaceContext()
{
}
public DogFaceContext(DbContextOptions<DogFaceContext> options)
: base(options)
{
Database.Migrate();
}
//Entity Tables
public virtual DbSet<Owner> Owners { get; set; }
public virtual DbSet<Cow> Cows { get; set; }
public virtual DbSet<Vaccination> Vaccination { get; set; }
public virtual DbSet<Weight> Weight { get; set; }
//Junction Tables
public virtual DbSet<OwnerCow> OwnerCows { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Cow>().HasMany(x => x.CowOwners).WithOne(x => x.Cow);
builder.Entity<Owner>().HasMany(u => u.CowOwners).WithOne(X => X.Owner);
builder.Entity("DogFace.API.Entities.OwnerCow", b =>
{
b.HasOne("DogFace.API.Entities.Cow", "Cow")
.WithMany("OwnerCows")
.HasForeignKey("CowId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("DogFace.API.Entities.Owner", "Owner")
.WithMany("OwnerCows")
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Restrict);
});
}
}
我可以让它与这个设计一起工作吗?EFCore可以吗?还有其他建议吗?谢谢!