【问题标题】:MVC/Code First: how to add more tables to the same db context?MVC/代码优先:如何将更多表添加到同一个数据库上下文?
【发布时间】:2015-04-11 11:18:05
【问题描述】:

我使用的是 VS 2013 附带的标准 MVC 模板。它有一个简洁的会员提供程序,使使用外部登录(Google、Facebook 等)变得轻而易举。还有关于如何扩展IdentityUser 模型以添加新属性(例如出生日期)的教程。

我想将更多表(我的应用程序)添加到已编码的数据库上下文中,以便享受相同的代码优先迁移功能。我该怎么做?当前db上下文定义如下:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

【问题讨论】:

    标签: asp.net-mvc entity-framework ef-code-first asp.net-identity asp.net-identity-2


    【解决方案1】:

    您正在使用 asp.net MVC5 身份 2,然后 ApplicationDbContext 已经存在于 IdentityModels.cs 中。因此您可以像这样添加表(DbSet)。

     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
    public ApplicationDbContext()
        : base("ApplicationDbContext", throwIfV1Schema: false)
    {
    }
    
    public DbSet<Department> Departments { get; set; }
    public DbSet<Student> Students { get; set; }
    
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    }
    

    【讨论】:

    • 谢谢!有用。我的下一个问题:如何重写 Seed 方法,以便在每次重新创建数据库时填充一些示例行?
    • 您好,您可以通过实现自定义数据库初始化程序并在那里覆盖种子方法来实现。看看这里:entityframeworktutorial.net/code-first/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2014-07-02
    • 2018-05-16
    • 1970-01-01
    • 2016-08-06
    相关资源
    最近更新 更多