Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you map subclass properties to columns in Table per Hierarchy?

Note: I think this is technically still code-first but I have an existing database as well so I'm not generating models or the database on the fly (no .edmx).

I have a TPH situation where the subclasses have fields specific to them. I have an EntityTypeConfiguration defined for the base class. How do I map the subclass-specific fields to columns in my database table?

public class Letter
{
    public string Name { get; set; }
}

public class A : Letter
{
    public int quantity { get; set; }
}

public class B : Letter
{
    public ComplexType description { get; set; }
}



public class LetterMap : EntityTypeConfiguration<Letter>
{
    HasKey...
}

This is EF 4.1.

Edit:

I've implemented the solution Eranga suggested below. My problem now is that two subclasses map different values to the same column. (A third subclass doesn't populate the column at all which is why I can move the property up a level).

(590,6) : error 0019: Each property name in a type must be unique. Property name 'Description_Title' was already defined.

For example:

B.description.title maps to the column "Description_Title"

while

C.description.shortTitle maps to the same column

like image 513
Jeff Swensen Avatar asked Dec 05 '25 01:12

Jeff Swensen


1 Answers

Make the Letter class abstract

public abstract class Letter
{
    public string Name { get; set; }
}

public class LetterMap : EntityTypeConfiguration<Letter>
{
    public LetterMap()
    {
        HasKey(l => l.Id);

        //assuming discriminator column is "Type"
        Map<A>(a => a.Requires("Type").HasValue<byte>(1));
        Map<B>(b => b.Requires("Type").HasValue<byte>(2));
    }
}

public class BMap : EntityTypeConfiguration<B>
{
    public LetterMap()
    {
          HasOptional(b => b.description)
            WithMany()
            HasForeignKey(b=> b.descriptionId);
    }
}
like image 183
Eranga Avatar answered Dec 06 '25 14:12

Eranga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!