EF Data First与ASP.NET Identity和MVC 5

时间:2017-09-13 22:33:15

标签: asp.net asp.net-mvc entity-framework

我使用个人用户帐户创建了一个ASP.NET MVC 5应用程序,用于身份验证和SQL Server 2012 Express。

该模板似乎有效。我可以创建帐户,管理我的用户帐户等。现在我想使用EF为我的应用程序创建其他表格,但我做错了,因为正在创建冲突的类(如ApplicationDbContext {})

基本上,我有我的默认AspNet数据库表,我想在EF Designer中看到它。我想在AspNetUsers表中添加一些字段。

我这样做的方式是"添加项目"然后我从数据库"。

中选择" EF Designer

在EF Designer中包含默认AspNet *表而不生成初始ASP.NET模板创建的冲突类的方法是什么?我正在使用VS 2015社区。

1 个答案:

答案 0 :(得分:3)

由于您使用的是Identity,因此我不会使用“Add Item”选项对您的数据库进行任何更改。

要向ApplicationUser模型添加新属性,请找到文件IdentityModels.cs。您应该看到类似于下面的内容。

public class ApplicationUser: IdentityUser
{
    // add new properties here
    public DateTime DateOfBirth { get; set; }
}

此文件也是您放置新表/模型的地方。

public class ApplicationDbContext: IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() 
        : base("DefaultConnection", throwIfVlSchema: false)
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    // Add new tables here
    public DbSet<NewModel> NewModels { get; set; }
}

完成任何更改后,您需要使用EF Data Migrations将这些更改提交到数据库。

要安装迁移,请使用程序包管理器控制台并键入Enable-Migrations

添加迁移类型add-migration [enter a description]

提交数据库类型update-database