[英]Foreign key mapping on Identifying Relationships
我在以下實體的前鍵關聯中面臨問題。
例如,存在三個實體,即一個,兩個和三個。 二靠一,就像三靠二。
另外,二將有許多三,一將有可能二(一對多)
由於2和3分別取決於1和2,因此我使用了確定關系 。 但是,當外鍵映射時,我在異常之下。
Two_Three_Source_Two_Three_Target ::關系約束中的從屬角色和主體角色中的屬性數必須相同
public class One
{
public long Id{get;set;}
public ICollection<Two> TwoList{get;set;}
}
public class Two
{
public long Id{get;set;}
public long OneId{ get; set; }
public ICollection<Three> ThreeList{get;set;}
}
public class Three
{
public long Id{get;set;}
public long TwoId{ get; set; }
}
public class OneMap: BaseEntityMap<One>
{
public OneMap()
{
this.HasKey(t => t.Id);
HasMany(t => t.Two).WithRequired().HasForeignKey(t => t.OneId);
ToTable("One");
}
}
public class TwoMap : BaseEntityMap<Two>
{
public TwoMap ()
{
this.HasKey(t => new { t.Id, t.OneId});
ToTable("Two");
HasMany(t => t.ThreeList).WithRequired().HasForeignKey(t => t.TwoId);
}
}
public class ThreeMap : BaseEntityMap<Three>
{
public ThreeMap ()
{
HasKey(t => new { t.Id, t.TwoId});
ToTable("Three");
}
}
我需要幫助以使用Fluent Mapping解決此問題
編輯
我這樣做的原因(確定關系)是為了使以下行工作(從db中刪除子記錄)
one.TwoList.Remove(item)
遵循模型並不簡單:)無論如何,問題出在三方面。 三個需要參考兩個。 二的主鍵是One.Id和Id(Two.Id)。 另一個問題可能是Id of Three(我認為應該是Id,TwoId,OneId,但可能不必使EF起作用)。
這里有一個例子。
public class Model9Context : DbContext
{
public Model9Context(DbConnection connection)
: base(connection, false)
{ }
public DbSet<One> Ones { get; set; }
public DbSet<Two> Twos { get; set; }
public DbSet<Three> Threes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new OneMap());
modelBuilder.Configurations.Add(new TwoMap());
modelBuilder.Configurations.Add(new ThreeMap());
}
}
public class One
{
public int Id { get; set; }
public ICollection<Two> TwoList { get; set; }
}
public class Two
{
public int Id { get; set; }
public int OneId { get; set; }
public virtual One One { get; set; }
public virtual ICollection<Three> ThreeList { get; set; }
}
public class Three
{
public int Id { get; set; }
public int TwoId { get; set; }
public int OneId { get; set; }
public virtual Two Two { get; set; }
}
public class OneMap : EntityTypeConfiguration<One>
{
public OneMap()
{
this.HasKey(t => t.Id);
ToTable("One");
}
}
public class TwoMap : EntityTypeConfiguration<Two>
{
public TwoMap()
{
this.HasKey(t => new { t.Id, t.OneId });
ToTable("Two");
HasRequired(t => t.One).WithMany(t => t.TwoList).HasForeignKey(t => t.OneId);
}
}
public class ThreeMap : EntityTypeConfiguration<Three>
{
public ThreeMap()
{
HasKey(t => new { t.Id, t.OneId, t.TwoId });
ToTable("Three");
HasRequired(t => t.Two).WithMany(t => t.ThreeList).HasForeignKey(t => new {t.OneId, t.TwoId});
}
}
這是EF在DBMS中定義的外鍵
ALTER TABLE [Three] ADD CONSTRAINT [FK_Three_Two_OneId_TwoId] FOREIGN KEY ([OneId], [TwoId]) REFERENCES [Two] ([Id], [OneId])
編輯
為了完整起見,通過此映射,EF將ID的ID字段作為自動增量生成,而將ID 2和3的ID字段不作為自動增量生成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.