Asp.net

ASP.NET Identity DbContext 混淆

  • November 11, 2013

IdentityModels.cs 中的這段程式碼帶有預設 MVC 5 應用程序 - 這段程式碼適用於預設模板的所有 ASP.NET Identity 操作:

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

如果我使用帶有實體框架的視圖建構一個新控制器並在對話框中創建一個“新數據上下文…”,我會為我生成這個:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
   public class AllTheOtherStuffDbContext : DbContext
   {
       // You can add custom code to this file. Changes will not be overwritten.
       // 
       // If you want Entity Framework to drop and regenerate your database
       // automatically whenever you change your model schema, please use data migrations.
       // For more information refer to the documentation:
       // http://msdn.microsoft.com/en-us/data/jj591621.aspx

       public AllTheOtherStuffDbContext() : base("name=AllTheOtherStuffDbContext")
       {
       }

       public System.Data.Entity.DbSet<WebApplication1.Models.Movie> Movies { get; set; }

   }
} 

如果我使用 EF 搭建另一個控制器 + 視圖,例如對於 Animal 模型,這條新行將在下面自動生成public System.Data.Entity.DbSet<WebApplication1.Models.Movie> Movies { get; set; }- 如下所示:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
   public class AllTheOtherStuffDbContext : DbContext
   {
       // You can add custom code to this file. Changes will not be overwritten.
       // 
       // If you want Entity Framework to drop and regenerate your database
       // automatically whenever you change your model schema, please use data migrations.
       // For more information refer to the documentation:
       // http://msdn.microsoft.com/en-us/data/jj591621.aspx

       public AllTheOtherStuffDbContext() : base("name=AllTheOtherStuffDbContext")
       {
       }

       public System.Data.Entity.DbSet<WebApplication1.Models.Movie> Movies { get; set; }
       public System.Data.Entity.DbSet<WebApplication1.Models.Animal> Animals { get; set; }

   }
} 

ApplicationDbContext(對於所有 ASP.NET 標識的東西)繼承自IdentityDbContext,而後者又繼承自DbContext. AllOtherStuffDbContext(對於我自己的東西)繼承自DbContext.

所以我的問題是:

我應該將這兩個 (ApplicationDbContextAllOtherStuffDbContext) 中的哪一個用於我自己的所有其他模型?或者我應該只使用預設的自動生成ApplicationDbContext,因為使用它應該不是問題,因為它是從基類派生的DbContext,還是會有一些成本?你應該DbContext在你的應用程序中為你的所有模型只使用一個對象(我已經在某處讀過這個)所以我什至不應該考慮在一個應用程序中同時使用這ApplicationDbContext兩者AllOtherStuffDbContext?或者在 MVC 5 中使用 ASP.NET Identity 的最佳實踐是什麼?

我將使用從 IdentityDbContext 繼承的單個 Context 類。這樣,您可以讓上下文了解您的類與 IdentityDbContext 的 IdentityUser 和 Roles 之間的任何關係。IdentityDbContext 的成本很小,它基本上是一個帶有兩個 DbSet 的正常 DbContext。一個用於使用者,一個用於角色。

引用自:https://stackoverflow.com/questions/19902756