views:

212

answers:

3

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

I have class 'Item', 'ContentBase' 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?

A: 

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 )

offir shvartz
A: 

Conclusion so far: Not possible.

Jeroen