在 Entity Framework 中设置 Table 关系 6

Setting Table Relationships in Entity Framework 6

我需要 EF6 中的结构,其中项目颜色可以有多个翻译。此结构是否支持该功能并且是否正确?

我正在尝试应用以下关系:

    [Table("PIMItem")]
    public class PIMItem  
    {
        [Key]
        public string Id {get;set;}//RowKey no.
        //there are additional columns in this item not related to color
        [ForeignKey("PIMColor")]
        [Column(Order=3)]
        public string ColorId {get;set;}
        public PIMColor PIMColor {get;set;}
    }

    [Table("PIMColor")]
    public class PIMColor
    {
        [Key]
        public string ColorId {get;set;}
        public ICollection<PIMItem> PIMItems {get;set;}
        public ICollection<PIMColorTranslation> PIMColorTranslation {get;set;}
    }

    [Table("PIMColorTranslation")]
    public class PIMColorTranslation{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column(Order=1)]
        public int Id {get;set;}
        [ForeignKey("PIMLanguage")]
        [Column(Order=2)]
        public string LanguageCode {get;set;}
        [ForeignKey("PIMColor")]
        [Column(Order=3)]
        public string ColorId {get;set;}
        public string Translation {get;set;}
    }

    [Table("PIMLanguage")]
    public class PIMLanguage{
        [Key] 
        public string LanguageCode {get;set;}
        public string Language {get;set;}
        public ICollection<PIMColorTranslation> PIMColorTranslation {get;set;}
    }

    public class SharedCtxt : DbContext 
    {
        public SharedCtxt() : base(sharedData.conn_string)
        {
        }
        public DbSet<PIMLanguage> PIMLanguages {get;set;}
        public DbSet<PIMColor> PIMColors {get;set;}
        public DbSet<PIMColorTranslation> PIMColorTranslations {get;set;}
        public DbSet<PIMItem> PIMItems {get;set;}

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

    }

对于 LanguageCodeColorId,您需要在 PIMColorTranslation 中有一个 unique 约束。 我不知道是否有相应的属性,但您可以使用 Fluent API:

protected override void OnModelCreating(ModelBuilder modelBuilder) {  
    ...
    modelBuilder.Entity<PIMColorTranslation>(entity =>
    {
        ...
        entity.HasIndex(e => new { e.LanguageCode, e.ColorId }).IsUnique();
        ...
    });  
    ...  
}

另注:
virtual 添加到导航属性。参见 why-use-virtual-for-class-properties-in-entity-framework-model-definitions

只是一个建议:
使用 Fluent API 配置架构。你不能用注释做很多事情,它确实会使代码膨胀。