2 回答

TA貢獻2039條經驗 獲得超8個贊
在 EF Core 中,每個關系都包含 0、1 或 2 個導航屬性。在大多數情況下,EF Core 可以自動確定關系及其關聯的導航屬性。但有時它不能,所以它會拋出異常,并希望您通過數據注釋、流式 API 或兩者的組合來明確指定。
在這種特殊情況下,異常消息告訴您 EF Core 無法確定EntityChildren.TransformedParents集合導航屬性表示的關系。您可以通過使用[InverseProperty]數據注釋將其與ParentEntity.TransformationEntity參考導航屬性配對來解決它:
[InverseProperty(nameof(EntityParent.TransformationEntity))]
public virtual ICollection<EntityParent> TransformedParents { get; set; }
在這種特殊情況下,這應該足夠了。
Fluent API 更加靈活,因為它們允許完全配置關系的所有方面 - 主體、依賴、導航屬性、依賴 FK 屬性、主體 PK 屬性、必需/可選、級聯刪除行為等。相應的 fluent 配置如下:
modelBuilder.Entity<EntityParent>()
.HasOne(p => p.TransformationEntity)
.WithMany(c => c.TransformedParents)
.HasForeignKey(p => p.TransformationEntityId) // optional (by convention)
.IsRequired(false) // optional (by convention)
.OnDelete(DeleteBehavior.ClientSetNull) // optional (by convention)
;

TA貢獻1835條經驗 獲得超7個贊
public class EntityChildren
{
public virtual ICollection<EntityParent> TransformedParents { get; set; }
和
public class EntityParent
{
public virtual ICollection<EntityChildren> Childrens { get; set; }
創建 EF Core 不支持的多對多關系。
必須有一個中間班來解決這個問題
比如一個類中間類 ParentChildren
public class ParentChildren
{
public int ParentId { get; set; }
public EntityParent Parent{ get; set; }
public int ChildId { get; set; }
public EntityChild Child{ get; set; }
}
然后,ICollection<ParentChildren>在你的EntityParent和EntityChild
數據庫上下文
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityParent>()
.HasKey(x => x.Id);
modelBuilder.Entity<EntityChild>()
.HasKey(x => x.Id);
modelBuilder.Entity<ParentChildren>()
.HasKey(x => new { x.ParentId , x.ChildId });
modelBuilder.Entity<ParentChildren>()
.HasOne(x => x.Parent)
.WithMany(m => m.Childrens)
.HasForeignKey(x => x.ParentId);
modelBuilder.Entity<ParentChildren>()
.HasOne(x => x.Child)
.WithMany(e => e.TransformedParents)
.HasForeignKey(x => x.ChildId);
}
- 2 回答
- 0 關注
- 206 瀏覽
添加回答
舉報