默認代碼MVC 5 App隨IdentityModels.cs中的這段代碼一起提供-此代碼段用于默認模板的所有ASP.NET Identity操作:public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{ public ApplicationDbContext() : base("DefaultConnection") { }}如果我使用帶有Entity Framework的視圖來搭建一個新的控制器并在對話框中創(chuàng)建一個“ New data context ...”,我將為我生成一個: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;ApplicaionDbContext(適用于所有ASP.NET Identity東西)繼承自IdentityDbContext,而繼承自DbContext。 AllOtherStuffDbContext(用于我自己的東西)繼承自DbContext。所以我的問題是:我所有其他自己的模型都應使用這兩個(ApplicationDbContext和AllOtherStuffDbContext)中的哪個?還是我應該只使用默認值autogenerated,ApplicationDbContext因為使用它應該不是問題,因為它是從基類派生的DbContext,否則會產(chǎn)生一些開銷嗎?你應該只使用一個DbContext在你的應用程序為所有的車型(我讀過這個地方)的對象,所以我不應該甚至考慮同時使用ApplicationDbContext,并AllOtherStuffDbContext在一個單一的應用程序?或帶有ASP.NET Identity的MVC 5中的最佳實踐是什么?
3 回答

茅侃侃
TA貢獻1842條經(jīng)驗 獲得超21個贊
我將使用從IdentityDbContext繼承的單個Context類。這樣,您可以使上下文知道您的類與IdentityUser和IdentityDbContext的角色之間的任何關(guān)系。IdentityDbContext的開銷很小,它基本上是帶有兩個DbSet的常規(guī)DbContext。一種用于用戶,另一種用于角色。

縹緲止盈
TA貢獻2041條經(jīng)驗 獲得超4個贊
如果深入研究IdentityDbContext的抽象,您會發(fā)現(xiàn)它看起來就像派生的DbContext。最簡單的方法是Olav的答案,但是如果您想對創(chuàng)建的內(nèi)容有更多的控制,并且對Identity軟件包的依賴性較小,請在此處查看我的問答。如果您單擊該鏈接,則會有一個代碼示例,但總而言之,您只需將所需的DbSet添加到您自己的DbContext子類中。
- 3 回答
- 0 關(guān)注
- 621 瀏覽
添加回答
舉報
0/150
提交
取消