Skip to main content
 首页 » 编程设计

c#之合并 DBContext 和 IdentityDbContext

2024年02月06日13mq0036

是否可以合并 DBContext 和 IdentityDbContext - 启用迁移,然后使用一个更新语句管理对我的数据库的代码优先更新?

即。在我的 IdentityModels.cs 文件中,我有:

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

在我的 tbContext.cs 文件中(当我添加模型类时创建的)我有:

namespace tb.Models 
{ 
public class tbContext : DbContext 
{ 
    public tbContext() : base("name=tbConn") 
    { 
        Database.SetInitializer<tbContext>(new tbInitializer<tbContext>()); 
    } 
    public System.Data.Entity.DbSet<tb.Models.Tour> Tours { get; set; } 
} 
} 
 
public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext> 
{ 
    protected override void Seed(tbContext context) 
    { 
        ApplicationDbContext userscontext = new ApplicationDbContext(); 
        var userStore = new UserStore<ApplicationUser>(userscontext); 
        var userManager = new UserManager<ApplicationUser>(userStore); 
 
        // Create user 
        if (!userscontext.Users.Any(x => x.UserName == "marktest")) 
        { var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" }; userManager.Create(user, "Pa$$w0rd!");} 
 
        var tour = new List<Tour> 
        { // seed database code }; 
        tour.ForEach(s => context.Tours.Add(s)); 
        context.SaveChanges(); 
    } 
} 

有什么方法可以合并这两个上下文,这样我就只有一个数据库和一个要管理的上下文?

感谢您的帮助,

标记

请您参考如下方法:

IdentityDbContext 默认继承自 DBContext。 无需创建新上下文(在您的情况下为 tbContext)- 只需从 IdentityModels.cs 中剪切并粘贴 ApplicationDbContext 并将其放入您的数据层。