2015-06-06 30 views
0

我正在嘗試執行以下操作...當user提交新的article時,我想在我的Web應用程序中顯示作者(用戶)用戶名。這就是爲什麼我需要「連接」這兩個,我想只有1個DbContext。如何正確地將ApplicationDbContext與您的自定義DbContext合併

我現在做這樣說:

public class ApplicationDbContext : IdentityDbContext 
{ 
    public DbSet<ApplicationUser> ApplicationUsers { get; set; } 
    private DbSet<Article> Articles { get; set; } // This line is all i have added/changed. Everything else was auto-generated when i created a new ASP.net MVC project with individual authentication in visual studio. 

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

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

,但我不知道這是做正確的方式。這應該如何正確完成?

UPDATE(我的評論的說明所DavidG的答案)

起初我是獲取用戶的列表,像這樣的:

class ApplicationUserService 
{ 
    public List<ApplicationUser> GetUsers() 
    { 
     using (var dbContext = new ApplicationDbContext()) 
     { 
      return dbContext.ApplicationUsers.ToList(); 
     } 
    } 
} 

代替:

class ApplicationUserService 
{ 
    public List<IdentityUser> GetUsers() 
    { 
     using (var dbContext = new ApplicationDbContext()) 
     { 
      return dbContext.Users.ToList(); 
     } 
    } 
} 

問題是因爲這個錯誤,我無法獲得用戶名或任何其他財產。我在線觀看了一些教程,沒有人提到DbSet是用戶。反正...現在我知道爲什麼我不需要這個屬性:

public DbSet<ApplicationUser> ApplicationUsers { get; set; } 

這從VS消息幫了我(意爲應該在同樣的問題,我不得不絆倒其他人):

'ApplicationDbContext.Users' hides inherited member 'IdentityDbContext<IdentityUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>.Users'. 
+0

什麼是'ApplicationUser'?它是否從'IdentityUser'繼承? – DavidG

+0

@DavidG是的,是的。 –

回答

3

如果您想使用一個上下文,並且Identity表與您的「文章」表位於同一個數據庫中,這很好。我通常喜歡重寫OnModelCreating,所以我可以爲我創建的表添加映射/配置。

根據應用程序的大小,我獨立保留Identity上下文,併爲應用程序創建一個(我可以包含Users表以便於檢索用戶)。一個選擇的問題。

1

您的應用程序只需要繼承正確版本的IdentityDbContext類。你需要使用通用的,所以你可以用你自己的IdentityUser自定義用戶類。所以你的背景應該是這樣的。請注意0​​屬性的新繼承和刪除。這是因爲Identity類已經爲你完成了。

public class ApplicationDbContext : IdentityDbContext<IdentityUser> 
{ 
    private DbSet<Article> Articles { get; set; } 

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

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

} 
+0

那麼我怎麼能從你的情況下從數據庫中獲取用戶的詳細信息?用戶的DbSet名稱是什麼? –

+0

現在明白了吧。請再次檢查我的問題。請確認我現在做的方式是正確的。謝謝! –

相關問題