0

Considering OOP it should not be possible but considerring EF and the way of inheritance works on a DB level, i am wondering if EF allows to jave to child class objects inherit from the same object at the same time. I mean.... Lets consider i have a table named person as the parrent table and have two tables that inherit from it named user and another named enployee. Since the inheritance mapping works in EF works by tracking the same primary key in the child table and parrent table, it should be possible to have the person class and be able to cast it either to the employee or user class. I suposse that some modifications would have to be made to the EF generated code.

4

1 回答 1

1

If polymorphism is a must then you need to use table per type (TPT) or table per hierarchy (TPH) inheritance. Use TPH for domain models with a lot tables and TPT when there are less tables as queries can become messy the larger a domain model is.

TPT represents the is a part of a relationship. A user is a person and a user is an employee. Going on what you've said in your question, you could use TPT like so:

public abstract class Person
{
    public int PersonId     { get; set; }   // EF will set this as PK
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}

[Table("User")]
public class User : Person
{
    public string SomeUserProperty { get; set; }
}

[Table("Employee")]
public class Employee : Person
{
    public string SomeEmployeeProperty { get; set; }
}

Then in your Context class you only create one DbSet which is of type base class:

public class MyDbContext: DbContext
{
    public DbSet<Person> Person { get; set; }
}

Then in some part of you application where you want to create instances of User or Employee:

using (var db = new MyDbContext())
{
    var user = db.Person.Create<User>();
    user.SomeUserProperty = "I'm a user";

    var emp = db.Person.Create<Employee>();
    emp.SomeEmployeeProperty = "I'm an employee";

    db.Person.Add(user);
    db.Person.Add(emp);
    db.SaveChanges();
}
于 2013-03-31T13:00:05.953 回答