Search code examples
asp.net-mvcentity-frameworkasp.net-mvc-4simplemembership

ASP.NET MVC 4 with Entity Framework and SimpleMembership linking data between tables


I currently have a ASP.NET MVC4 application in which I am trying to set up SimpleMembership for user accounts. So far, I have a database setup automatically with EF code first migrations and have gotten it to generate the SimpleMembership tables in my database.

I would like to have it set up so that there is a relationship between user that is currently logged in and a specific entity that I have created. I have two different types of users: Students & Teachers. Both of these are derived from a base "User" class.

For example: When a student logs in, he/she will have access to things such as their account and other data stored in a separate student table different from the "UserProfile" table created by EF.

I have done some research into implementing this and I believe that I need to create a link using "UserId" as a foreign key attribute for the users. But what are the next steps I need to take after that to actually be able to store information into different tables?

What is the best approach to take for tying together data from the SimpleMembership table and the Student table through the UserId key?

Here are my user classes with what I believe is the correct way to set up the relationship between the two.

User

    public class User
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    [Display(Name = "First Name")]
    [Required(ErrorMessage = "First name is required.")]
    [MaxLength(50)]
    public virtual string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Last name is required.")]
    [MaxLength(50)]
    public virtual string LastName { get; set; }
}

Student

    public class Student : User
{
    public virtual ICollection<Account> Accounts { get; set; }
}

Teacher

public class Teacher : User
{
    public virtual ICollection<Student> Students { get; set; }
    public virtual ICollection<Classroom> Classrooms { get; set; }
}

Solution

  • You could generate Configuration classes that inherit from EntityTypeConfiguration, where T is your model class (Account, Student or Classroom in your case). Using the fluent API, you could create the many-to-many relationship, such as many students may have many accounts; the junction table of Student_x_Account could then represent the relationship of STUDENT_ID to ACCOUNT_ID.