2014-10-19 61 views
6

我無法理解整個ASP.Net身份框架,我首先嚐試將Identity 1.0集成到現有的應用程序中,但是我最終得到了2個DbContext類,我的應用程序數據位於MyDbContext上,和IdentityDbContext上的Identity用戶數據。擴展ASP.NET身份2.0

我想爲我的應用程序數據和身份相關數據使用單個DbContext,並且在另一個問題上發現我可以像使用DbContext一樣使用IdentityDbContext;不過,我想我錯過了一些東西。

我使用的是從身份團隊

PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre 

示例項目,並試圖插入DbSet性質的ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext 
{ 
    public ApplicationDbContext() 
     : base("DefaultConnection") 
    { 
    } 

    static ApplicationDbContext() 
    { 
     // Set the database intializer which is run once during application start 
     // This seeds the database with admin user credentials and admin role 
     Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); 
    } 

    public virtual DbSet<Student> students { get; set; } 
    public virtual DbSet<Teachers> teachers { get; set; } 

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

我使用ApplicationDbInitializer種方法來填充那些2表,這樣的事情:

Student s = new Student { Name = "John" ... }; 
db.students.Add(s); 
db.SaveChanges(); 

但EF似乎並不創建這兩個表,並且種子方法沒有被調用,發生了什麼?

編輯:

好吧,我需要運行使用數據庫EF刪除並重新創建數據庫的代碼。

使用IdentityDbContext管理我所有的應用程序數據是否有任何開銷? 使用IdentityDbContext和使用通用版本IdentityDbContext < IdentityUser>有什麼區別?

回答

4

在大多數情況下,只使用一個實體框架上下文是首選,因爲那樣你只需要管理那一個,這意味着更少的開銷。

兩者之間的區別在於IdentityDbContext僅僅是一個從DbContext派生的類(就像您在創建自己的時候一樣),但它包含處理身份驗證的其他DbSets,因此您不必親自實現它。從IdentityDbContext派生是好的。欲瞭解更多信息,你可以看看documentation