0

仅使用 EF 4.0 代码我想在抽象类和普通类之间建立关联。

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

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

“ContentBase”有一个属性“Item”,它链接到“Item”的一个实例。

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

在我的数据库中,Test 的每条记录都有 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”注册密钥。

无论如何,我尝试我得到一个错误。我做错了什么?

4

3 回答 3

0

导航属性 Item 在基本类型级别定义,因此模型知道基本类型 - 您可以将属性添加到传递 Item 属性的测试类并将其映射到您的关系中:

public class Test : ContentBase
{
    public string Name { get; set;}
    public string TestItem { get {return Item;} ...

}

testConfig.Relationship(p => p.TestItem )
于 2010-05-16T13:27:53.397 回答
0

到目前为止的结论:不可能。

于 2010-07-23T16:43:41.270 回答
0

尝试在超类型实体中重新声明您的关系:

在 ContentBase 中: public virtual Item Item { get; 放;}

测试中:public new Item Item { get; 放;}

这在我的测试项目中编译,但我没有进一步测试它。就目前而言,wheb EF5 或最终登场

于 2010-11-06T13:33:24.823 回答