【问题标题】:Overriding EF CodeFirst Generated Database覆盖 EF 代码优先生成数据库
【发布时间】:2011-01-10 21:24:39
【问题描述】:

我有一个使用 EF CodeFirst 方法的 C# 项目。我的问题是 EF 如何解释我的类并生成数据库表。 EF 推断出太多东西,而我得到的数据库不是我想要的方式。具体来说,它正在我的一个映射类中生成额外的 id 列。

这是我的 POCO 课程:

    public partial class Attribute
    {
    public int Id {get;set;}
    public string Name {get;set;}
    public virtual ICollection<EntityAttribute> EntityAttributes {get;set;}
    }

    public partial class Grant
    {
    public int Id {get;set;}
    public string Name {get;set;}
    public virtual ICollection<EntityAttribute> EntityAttributes {get;set;}
    }

    public partial class Donor
    {
    public int Id {get;set;}
    public string Name {get;set;}
    public virtual ICollection<EntityAttribute> EntityAttributes {get;set;}
    }

    public enum EntityTypeEnum
    {
    Grant = 1,
    Donor = 2
    }

    public partial class EntityAttribute
    {
    public int Id {get;set;}
    public int EntityId {get;set;}
    public int AttributeId {get;set;}
    public int EntityTypeId {get;set;}
    public EntityTypeEnum EntityType
    {
       get{return (EntityTypeEnum)this.EntityTypeId;}
       set{this.EntityTypeId = (int)value;}
    }
    public virtual Grant Grant {get;set;}
    public virtual Donor Donor {get;set;}
}

我的映射类是典型的,但这里是 EntityAttributeMap 类:

public partial class EntityAttributeMap : EntityTypeConfiguration<EntityAttribute>
{
public EntityAttributeMap()
{
this.ToTable("EntityAttribute");
this.HasKey(ea => ea.Id);
this.Property(ea => ea.EntityTypeId).IsRequired();
this.Ignore(ea => ea.EntityType);

this.HasRequired(ea => ea.Grant)
    .WithMany(g => g.EntityAttributes)
    .HasForeignKey(ea => ea.EntityId);

this.HasRequired(ea => ea.Donor)
    .WithMany(d => d.EntityAttributes)
    .HasForeignKey(ea => ea.EntityId);

this.HasRequired(ea => ea.Attribute)
    .WithMany(a => a.EntityAttributes)
    .HasForeignKey(ea => ea.AttributeId)
}
}

我的所有单元测试都按预期执行。但是,表 EntityAttribute 使用 DonorId 和 GrantId 列呈现。我不想要这个,因为我实际上有许多其他“EntityTypes”将用于这种情况。这就是我选择 EntityTypeEnum 类的原因。

我做错了什么?或者是否有另一种方式我应该映射这些以便 EF 以我想要的方式处理事情。谢谢。

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:

    The EF doesn't support enums at all, as of V4 CTP 5. They might be included in the next release.

    话虽如此,但架构看起来(对我而言;从您的帖子中并不清楚,您的意图可能不同)太接近 EAV 以使我感到安慰。由于通常的原因(谷歌搜索)我不喜欢这些,即使在 EF 中支持 enum 也不想要那种模型。

    为什么不映射到另一个实体类型而不是枚举?

    如果您以“以下是我的业务需求;对此的最佳架构是什么?”的形式提出问题?您可能会得到更好的答案。

    【讨论】:

    • 我想我正按照你的建议转向 EAV。我只是想提高效率。鉴于我将有许多实体映射到我的属性表,您是否建议为每个实体/属性组合或一个映射表中的多个实体 id 列使用单独的映射表。我想这样做的缺点是有很多空值。另外,感谢您提出的问题框架建议。
    • 大量空值可能不是问题。例如,SQL Server 2008+ 允许您声明列 SPARSE,它告诉服务器“针对大多数 NULL 进行优化”。
    • 哦,关于一张表与多张表,请阅读 EF 中的 TPH 与 TPT 继承建模。即使您本身没有进行继承, 性能考虑也是相同的。
    • 谢谢克雷格。我可能会选择一张表并针对 NULLS 进行优化(我不了解 SQL Server)。这是一个后台应用程序,最多只有几十个用户。不过,我会看看你的阅读建议。再次感谢。
    猜你喜欢
    • 2012-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多