首页 文章

带有Identity 2.0的Asp.net MVC 5中的DbContext类

提问于
浏览
0

在使用Entity Framework时,需要有一个派生自DbContext的上下文类 .

Asp.net Identity使用EF,默认模板创建以下类:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

此类不从DbContext派生 directly . 对于我自己的数据(我希望持久保存到db的类),我应该创建自己的db上下文类吗?

如果我想做一个将更新身份用户和我自己的类之一的操作,我需要使用两个上下文 . 所以这感觉不太自然 .

我应该继续使用ApplicationDbContext类作为我自己的类的上下文吗?那会有用吗?

在使用身份时,为自己的类使用EF的最佳方法是什么?

1 回答

  • 2

    使用从IdentityDbContext继承的单个Context类 . 有关详细信息,请参阅this answer .

    您需要将所有类的DbSet添加到ApplicationDbContext中 .

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
        : base("DefaultConnection", false)
        {
        }
    
        //Public DBSets
        public DbSet<LeaveApplication> LeaveApplications { get; set; }
        public DbSet<LeaveStatus> LeaveStatus { get; set; }
        public DbSet<Department> Departments { get; set; }
    
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
    

相关问题