Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc 5 code first userid as a Foreign Key

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")
    {
    }
}
like image 750
noon Avatar asked Jan 30 '14 19:01

noon


1 Answers

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).

like image 152
Brad Christie Avatar answered Oct 10 '22 04:10

Brad Christie