开发者

polymorphic association and splitting tables

I have 3 tables in my SQL Server database:

  • Teacher
  • Student
  • Parent

Each of these tables contains some columns which are also found in the others, for example:

  • FirstName
  • Surname

All the other columns are different. This is a legacy database. I can’t change it.

In my C# code, I would like to have:

public partial class Person
{
    public string FirstName { get; set; }
    public string Surname { get; set; }

    public virtual ICollection<Role> Roles { get; set; }
}

public interface Role
{
}

public partial class Teacher : Role
{   
    public string School { get; set; }
}

public partial class Student : Role
{
    public string YearLevel { get; set; }
}

public partial class Parent : Role
{
    public string Blagh { get; set; }
}

That is, a polymorphic many-to-on开发者_如何学Goe association between Role and Person.

The reason I want this is because a person can be both a teacher and a parent.

My question is, what technology should I use to populate the business objects from the database?

I’ve looked at Entity Framework 4.1 DbContext stuff; I like the data annotation approach, but can it do what I want? If not, can the Fluent API?

If the Entity Framework can’t do this, then how about NHibernate (preferably using attributes), or Linq-to-SQL?

I know NHibernate can handle a polymorphic association, but can this be done where we are splitting the tables between entities like here?


The closest you can get with Entity framework is TPC inheritance:

public abstract class Person
{
    public string FirstName { get; set; }
    public string Surname { get; set; }
}

public partial class Teacher : Person
{   
    public string School { get; set; }
}

public partial class Student : Person
{
    public string YearLevel { get; set; }
}

public partial class Parent : Person
{
    public string Blagh { get; set; }
}

Nothing more because:

  • EF is not able to map multiple entities to the same table without inheritance or table splitting
  • EF is not able to map multiple relations to single navigation property
  • Teacher and Parent will always be two different not related persons.

I doubt that NHibernate supports this because what you shown is not pure polymorphic association (there is still problem with non deterministic mapping of Person) but perhaps somebody will surprise me.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜