实体框架-代码优先-具有共享主键的一对多关系
本文关键字:共享 关系 一对多 -具 框架 代码 实体 | 更新日期: 2023-09-27 18:29:37
任何人都知道如何使用EF Code First Fluent API实现此场景:
public class Referancial
{
// Identity
public int KeyID { get; set; }
public string Code { get; set; }
public virtual ICollection<Translation> Translations { get; set; }
}
public class Translation
{
// refer to Referancial.KeyID
public int KeyID { get; set; }
public int LanguageID { get; set; }
public string Label { get; set; }
}
感谢您的回复
尝试另一种型号,我认为它更适合你
public class Referancial
{
// Identity
public int KeyID { get; set; }
public string Code { get; set; }
public virtual ICollection<Translation> Translations { get; set; }
}
public class Translation
{
//Translation needs its own Key
public int ID { get; set; }
// reference directly the Referencial object instead of the ID
public Referencial Referencial { get; set; }
public int LanguageID { get; set; }
public string Label { get; set; }
}
配置您的型号
_modelBuilder.Entity<Referancial>().HasKey(r => r.KeyID);
_modelBuilder.Entity<Translation>().HasKey(t => t.ID);
_modelBuilder.Entity<Referancial>().HasMany(r => r.Translations).WithRequired(t => t.Referencial).WillCascadeOnDelete(true);
//创建模型时:
protected覆盖void OnModelCreating(DbModelBuilder modelBuilder){
// Person
modelBuilder.Entity<Person>().HasKey(e => e.PersonID)
.ToTable("Persons")
.Property(e => e.PersonID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//Referancial
modelBuilder.Entity<Referancial>().HasKey(e => e.KeyID)
.ToTable("Referancials")
.Property(e => e.KeyID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
//Translation
modelBuilder.Entity<Translation>().ToTable("Translations")
.HasKey(e => e.KeyID)
.Property(e => e.KeyID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Referancial>()
.HasOptional(e=>e.Translations)
.WithMany()
.HasForeignKey(e => e.KeyID);
base.OnModelCreating(modelBuilder);
}
但它告诉我一个错误:
在模型生成过程中检测到一个或多个验证错误:
PersonSearch.Models.Referencial_Translations::多重性与关系"Referencial_Translations"中角色"Referencil_Translations_Target"中的引用约束冲突。由于Dependent Role中的所有属性都不可为null,因此Principal Role的多重性必须为"1"。Referencial_Translations_Source::多重性在关系"Referencial_Translations"中的角色"Referencil_Translations_Source"中无效。由于Dependent Role引用了键属性,因此Dependent Role的多重性的上限必须为"1"。