mvc 5将第一个用户ID作为外键

noo*_*oon 9 asp.net-mvc code-first ef-code-first asp.net-mvc-5

我有一张桌子:

public class TestModel
{
    public int Id { get; set; }
    public string UserId { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望UserId列是外键,Mvc Membership的用户ID列.我怎么能得到这个?

我的IdentityModels:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*tie 20

添加对该引用的引用ApplicationUser并指定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; }
}
Run Code Online (Sandbox Code Playgroud)

将新模型添加到DbContext:

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

    /* rest of class */
}
Run Code Online (Sandbox Code Playgroud)

而且你应该很好(可以减少迁移/数据库更新).