mvc 5 code first userid as a Foreign Key

asp.net-mvc, asp.net-mvc-5, code-first, ef-code-first

Solution

Add a reference to the `ApplicationUser` and specify the ForeignKey:

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

    public string UserId { get; set; }
    [ForeignKey("UserId")]
    public ApplicationUser User { get; set; }
}

Add the new model to your DbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<TestModel> TestModels { get; set; }

    /* rest of class */
}

And you should be good-to-go (less migrations/database updates).

Problem

I have a table: ``` public class TestModel { public int Id { get; set; } public string UserId { get; set; } public string Name { get; set; } } ``` I want UserId column to be a foreign key, Mvc Membership's User's Id column. How can I achive this? My IdentityModels: ``` public class ApplicationUser : IdentityUser { } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { } } ```

Original source