【问题标题】:EntityFramework Code First inheritance with custom discriminatorEntityFramework Code First 继承与自定义鉴别器
【发布时间】:2013-02-03 20:28:07
【问题描述】:

我正在尝试在 EntityFramework Code First 中映射以下继承

public class Member
{
    public string ProjectName { get; set; }
    public string AssemblyName { get; set; }
    public string NamespaceName { get; set; }
    public string TypeName { get; set; }
    public string Signature { get; set; }
    public string DisplayName { get; set; }
    public MemberType Type { get; set; }
    public string Summary { get; set; }
    public bool IsStatic { get; set; }
    public bool IsInherited { get; set; }

    //public virtual Type ParentType { get; set; } // ignore this
}

public class Field : Member
{
    public string ValueType { get; set; }
    public bool IsReadOnly { get; set; }
    public bool IsVolatile { get; set; }
}

public enum MemberType
{
    Constructor,
    Field,
    Method,
    Operator,
    Property
}

正如您可能从代码中猜到的那样,我计划及时添加更多成员的子类(命名为构造函数、方法、运算符和属性),但首先我只想让字段之一正常工作。

我的映射代码如下所示

modelBuilder.Entities<Member>().Configure(config =>
{
    config.HasKey(m => new { m.ProjectName, m.AssemblyName, m.NamespaceName, m.TypeName, m.Signature });
    config.Property(m => m.DisplayName).IsRequired();
    config.ToTable("Members");
});

modelBuilder.Entities<Field>().Configure(config =>
{
    config.HasKey(f => new { f.ProjectName, f.AssemblyName, f.NamespaceName, f.TypeName, f.Signature });
});

modelBuilder.Entity<Member>()
    .Map<Field>(m => 
    {
        m.ToTable("Fields");
        m.Requires("Type").HasValue((int)Service.DataTypes.MemberType.Field).IsRequired();
    }); // note: realy not certain about this one

我想要的是生成两个表。一个名为“Members”,一个名为“Fields”,并使用Member-class 中的Type-property 作为鉴别器,我确定我只是在这里做一些非常愚蠢的事情,但我不能为我的一生弄清楚该怎么做。因为使用当前代码,它会在“字段”表中生成一个名为“类型”的列,您显然不需要它,因为它是一个常量。

所以我只是想知道,有人能告诉我我到底做错了什么吗?

【问题讨论】:

    标签: c# entity-framework inheritance ef-code-first


    【解决方案1】:

    那里有错字吗?您的类有一个字段 Valuetype Not Type。

    我从未尝试过仅使用 1 个映射,请尝试使用第二个表以确保。

    modelBuilder.Entity<Member>()
    .Map<Field>(m => 
    {
        m.ToTable("Fields");
        m.Requires("ValueType").HasValue((int)Service.DataTypes.MemberType.Field).IsRequired();
    })
    .Map<SECONDTYPE>(m =>
    {
        m.Requires("ValueType").HasValue(42);
    }); 
    

    【讨论】:

    • 不,没有错字。它是一个名为 ValueType 的字符串属性。但是,添加第二个表就可以了。
    • @Alxandr 我在这里遇到了同样的问题,你添加了什么而不是 SECONDTYPE 和 .HasValue(42)?
    猜你喜欢
    • 1970-01-01
    • 2011-09-27
    • 2013-03-04
    • 2012-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 2011-03-26
    相关资源
    最近更新 更多