每个层次表和多对多关系

时间:2013-08-06 17:02:08

标签: entity-framework entity-framework-4 ef-code-first many-to-many

这似乎很容易解决,但我遇到的复杂情况是每个层次结构都有一个表来存储所有实体,而我无法在同一个表上创建关系。以下是我在DB和类中的内容:

enter image description here

我只有一个名为BaseObject的表,其中包含ID,名称和类型。我将为存储在那里的那些实体创建两个类。主人和组件。 type列是鉴别器。我有另一个表来存储两者之间的关系:一个master可以有很多组件,一个组件也可以有许多其他组件。

这是我为课程编写的代码:

public partial class BaseObject
{
    public BaseObject()
    {

    }

    public System.Guid ID { get; set; }
    public string Name { get; set; }
    public Nullable<int> Type { get; set; }
}

public class MasterObject : BaseObject
{
    public virtual ICollection<ComponentObject> Components { get; set; }

    public MasterObject()
    {
        this.Components = new List<ComponentObject>();
    }
}

public class ComponentObject : BaseObject
{
    public virtual ICollection<MasterObject> MasterObjects { get; set; }

    public ComponentObject()
    {
        this.MasterObjects = new List<MasterObject>();
    }
}

这些是映射:

public class BaseObjectMap : EntityTypeConfiguration<BaseObject>
{
    public BaseObjectMap()
    {
        // Primary Key
        this.HasKey(t => t.ID);

        // Table & Column Mappings
        this.ToTable("BaseObject");
        this.Property(t => t.ID).HasColumnName("ID");
        this.Property(t => t.Name).HasColumnName("Name");

        //configure the inheritance in here
        this.Map<MasterObject>(m => m.Requires("Type").HasValue(1));
        this.Map<ComponentObject>(m => m.Requires("Type").HasValue(2));
    }
}

public class MasterObjectMap : EntityTypeConfiguration<MasterObject>
{
    public MasterObjectMap()
    {
        this.HasMany<ComponentObject>(t => t.Components)
            .WithMany(t => t.MasterObjects)
            .Map(c =>
            {
                c.ToTable("ObjectComponents");
                c.MapLeftKey("ComponentObjectID");
                c.MapRightKey("BaseObjectID");
            });
    }
}

public class ComponentObjectMap : EntityTypeConfiguration<ComponentObject>
{
    public ComponentObjectMap()
    {
        this.HasMany<MasterObject>(t => t.MasterObjects)
            .WithMany(t => t.Components)
            .Map(m =>
            {
                m.ToTable("ObjectComponents");
                m.MapLeftKey("BaseObjectID");
                m.MapRightKey("ComponentObjectID");
            });
    }
}

问题在于,当查询数据库时,我可以通过访问DBSet Masters获得Master,但是Component集合总是给出一个无意义的异常,说“从第6行开始映射片段的问题:条件成员'BaseObject映射除了'IsNull = False'之外的条件'。'删除BaseObject.Type上的条件或从映射中删除它。“

我不明白发生了什么。当然,如果指向每个表的类,这将是非常容易的,但我怀疑这是我的问题的根源。

另外,我刚开始使用EF。我想根据我现在不想修改的现有数据库创建类。除非真的需要它。请指导我,如果我正在尝试做的是对还是错,或者我应该首先在目前使用NHibernate的这个项目上完全实现EF。

这里有什么帮助吗?感谢

1 个答案:

答案 0 :(得分:2)

最后,由于这个答案,我发现了这个问题:EF4.1 Exception creating Database with table-per-hierarchy inheritance

问题在于Base类的映射。当使用基类和鉴别器来获取子类时,鉴别器绝不应该是属性。刚删除鉴别器作为财产,它工作正常。在我的例子中,'Type'列是鉴别器。

希望这有助于其他人。

相关问题