实体框架 - 代码优先 - 与共享主键的一对多关系

时间:2014-11-06 16:24:00

标签: c# .net entity-framework ef-fluent-api

任何人都知道如何使用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; }

}

感谢您的回复

2 个答案:

答案 0 :(得分:1)

尝试使用其他型号,我认为它更适合您

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);

答案 1 :(得分:0)

//在模型创建上:

protected override 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.Referancial_Translations ::多重性与角色&Referancial_Translations_Target&#39; Referancial_Translations_Target&#39;中的参照约束冲突。在关系&Referancial_Translations&#39;。由于从属角色中的所有属性都是不可为空的,因此主要角色的多重性必须为“1”。 Referancial_Translations_Source :: Multiplicity在Role&Referancial_Translations_Source&#39;中无效。在关系&Referancial_Translations&#39;。由于“从属角色”是指关键属性,因此“从属角色”的多重性的上限必须为“&#39; 1”。