Entity Framework inheritance composite key

665 views Asked by At

Here's my scenario: I have three entities types, User(id, email, password), Volunteer(name, birthdate...) and NonProfit(address...). Both Volunteer and NonProfit are User.

I was able to create three tables like tbUser, tbVolunteer and tbNonProfit, where user has a primary key, and volunteer and nonprofit has primary/foreign key of user(UserID), but I don't want this.

My user is not an abstract class. First I will create an user, for example Mary, and I will say that Mary is of type Volunteer. In a next moment, Mary will log in and complete the registration, so I will create a volunteer row on database.

In short, I would like that the volunteer table had UserID as foreign key and VolunteerID(primary key) in order to keep it equals my engineering diagrams, where volunteer and nonprofit are users. I don't want an aggretation or composition because in my UML volunteer inherits from user.

I'm open for suggestions, thank y'all

1

There are 1 answers

3
Rob Tillie On BEST ANSWER

The correct way to implement this is to not have another primary key. The implementation looks like this:

public class User
{
    [Key]
    public int UserId { get; set; }

    public string Email{ get; set; }
    public string Password { get; set; }
}

[Table("Volunteer")]
public class Volunteer : User
{
    public DateTime BirthDate { get; set; }
}

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

public class MyContext: DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Volunteer> Volunteers { get; set; }
    public DbSet<NonProfit> NonProfits { get; set; }
}

For more information, have a look at this article: http://www.codeproject.com/Articles/796521/Inheritance-in-Entity-Framework-Table-Per-Type