开发者

EF 4.0 Code only assocation from abstract to derived

开发者 https://www.devze.com 2022-12-20 02:00 出处:网络
Using EF 4.0 Code only i want to make an assocation between an abstract and normal class. I have class \'Item\', \'ContentBa开发者_开发技巧se\' and \'Test\'.

Using EF 4.0 Code only i want to make an assocation between an abstract and normal class.

I have class 'Item', 'ContentBa开发者_开发技巧se' and 'Test'.

'ContentBase' is abstract and 'Test' derives from it.

'ContentBase' has a property 'Item' that links to an instance of 'Item'.

So that 'Test.Item' or any class that derives from 'ContentBase' has an 'Item' navigation property.

In my DB every record for Test has a matching record for 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;}
}

now some init code

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);  
}

This gives an error: A key is registered for the derived type 'Test'. Keys must be registered for the root type 'ContentBase'.

anyway i try i get an error. What am i a doing wrong?


Conclusion so far: Not possible.


Try in suppertype entity to redeclare your relationship:

In ContentBase: public virtual Item Item { get; set;}

In Test: public new Item Item { get; set;}

This compiled in my test project, but i didn't test it further. Just for the time being, wheb EF5 or final comeso


The navigation property Item is define in the base type level, so the model is aware of the base type - you can add property to the test class which pass the Item property and map it in your relation:

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

}

testConfig.Relationship(p => p.TestItem )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号