代码之家  ›  专栏  ›  技术社区  ›  Jeroen

EF 4.0从抽象到派生的仅代码关联

  •  0
  • Jeroen  · 技术社区  · 15 年前

    仅使用ef4.0代码,我想在抽象类和普通类之间建立关联。

    我有“Item”、“ContentBase”和“Test”类。

    “ContentBase”是抽象的,“Test”派生自它。

    因此,“Test.Item”或从“ContentBase”派生的任何类都具有“Item”导航属性。


    public class Item
    {
        public int Id { get; set;}
    }
    
    public abstract class ContentBase
    {
        public int ContentId { get; set;}
        public int Id { get; set;}
    
        public Item Item { get; set;}
    }
    
    public class Test : ContentBase
    {
        public string Name { get; set;}
    }
    

    现在是一些初始化代码

    public void SomeInitFunction()
    {
    
        var itemConfig = new EntityConfiguration<Item>();
        itemConfig.HasKey(p => p.Id);
        itemConfig.Property(p => p.Id).IsIdentity();
        this.ContextBuilder.Configurations.Add(itemConfig);
    
        var testConfig = new EntityConfiguration<Test>();
        testConfig.HasKey(p => p.ContentId);
        testConfig.Property(p => p.ContentId).IsIdentity();
    
        // the problem 
        testConfig.Relationship(p => p.Item).HasConstraint((p, q) => p.Id == q.Id);
    
        this.ContextBuilder.Configurations.Add(testConfig);  
    }
    

    这会产生一个错误: 已为派生类型“Test”注册密钥。必须为根类型“ContentBase”注册密钥。

    不管怎样,我试着我得到一个错误。我做错什么了?

    3 回复  |  直到 14 年前
        1
  •  0
  •   Jeroen    14 年前

    目前结论:不可能。

        2
  •  0
  •   atam    14 年前

    尝试在suppertype实体中重新声明您的关系:

    在ContentBase中: 公共虚拟项{get;集合;}

    public new Item{get;集合;}

    这是我在测试项目中编译的,但我没有进一步测试它。 只是暂时的,是EF5还是最后的结果呢

        3
  •  0
  •   Sicco    12 年前

    导航属性项是在基类型级别定义的,因此模型知道基类型-您可以将属性添加到传递项属性和 把它映射到你的关系中:

    public class Test : ContentBase
    {
        public string Name { get; set;}
        public string TestItem { get {return Item;} ...
    
    }
    
    testConfig.Relationship(p => p.TestItem )