1

I am using Table-Per-Hierarchy pattern (same DB table for all derived classes), like this:

Base class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

A few derived classes, some of them having Address, like this:

public class Student : Person
{
    public virtual Address Address { get; set; }
}

public class Teacher : Person
{
    public virtual  Address Address { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public string Street { get; set; }
}

Unfortunately, when the database is created, a new column is created for every address foreign key like this: Address_Id, Address_Id1 ... Address_IdN

It is possible to overcome it by explicitly adding foreign key to every class using Address like this:

public class XXX : Person
{
    [Column("AddressId")]
    public virtual int AddressId { get; set; }


    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }

}

However, this solution requires having AddressId property in the classes which is undesirable. It cannot be hidden declaring as private or protected, because table mapped property must be public.

I thought of using fluent API like this:

        modelBuilder.Entity<Student>()
            .HasOptional(s => s.Address)
            .WithRequired(a => (a.Person as Student));

or

        modelBuilder.Entity<Address>()
                    .HasRequired(a => a.Person)
                    .WithOptional(s => (s as Student).Address);

but there is a problem with casting between the base and the derived class. Now I am stuck…

Tomas
  • 449
  • 5
  • 11

0 Answers0