【问题标题】:Setting Table Relationships in Entity Framework 6在 Entity Framework 6 中设置表关系
【发布时间】:2022-01-19 16:21:12
【问题描述】:

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

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

  • 每个 PIMItem 有 1 个 PIMColor
  • 每个 PIMColor 可以有多个 PIMColorTranslations
  • 每个语言代码的每种颜色只允许 1 个 PIMColorTranslation。
    [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>();
        }

    }

【问题讨论】:

    标签: c# entity-framework-6


    【解决方案1】:

    对于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 配置架构。注释不能做太多事情,而且它确实会使代码膨胀。

    【讨论】:

    • 感谢您的反馈!
    猜你喜欢
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多