默認(rèn)代碼MVC 5 App隨IdentityModels.cs中的這段代碼一起提供-此代碼段用于默認(rèn)模板的所有ASP.NET Identity操作:public class ApplicationDbContext : IdentityDbContext<ApplicationUser>{ public ApplicationDbContext() : base("DefaultConnection") { }}如果我使用帶有Entity Framework的視圖來搭建一個(gè)新的控制器并在對(duì)話框中創(chuàng)建一個(gè)“ New data context ...”,我將為我生成一個(gè):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搭建另一個(gè)控制器+視圖,例如為Animal模型,則此新行將在下面自動(dòng)生成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。所以我的問題是:我所有其他自己的模型都應(yīng)使用這兩個(gè)(ApplicationDbContext和AllOtherStuffDbContext)中的哪個(gè)?還是我應(yīng)該只使用默認(rèn)值autogenerated,ApplicationDbContext因?yàn)槭褂盟鼞?yīng)該不是問題,因?yàn)樗菑幕惻缮腄bContext,否則會(huì)產(chǎn)生一些開銷嗎?你應(yīng)該只使用一個(gè)DbContext在你的應(yīng)用程序?yàn)樗械能囆停ㄎ易x過這個(gè)地方)的對(duì)象,所以我不應(yīng)該甚至考慮同時(shí)使用ApplicationDbContext,并AllOtherStuffDbContext在一個(gè)單一的應(yīng)用程序?或帶有ASP.NET Identity的MVC 5中的最佳實(shí)踐是什么?
3 回答

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

縹緲止盈
TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果深入研究IdentityDbContext的抽象,您會(huì)發(fā)現(xiàn)它看起來就像派生的DbContext。最簡(jiǎn)單的方法是Olav的答案,但是如果您想對(duì)創(chuàng)建的內(nèi)容有更多的控制,并且對(duì)Identity軟件包的依賴性較小,請(qǐng)?jiān)诖颂幉榭次业膯柎稹H绻鷨螕粼撴溄?,則會(huì)有一個(gè)代碼示例,但總而言之,您只需將所需的DbSet添加到您自己的DbContext子類中。
- 3 回答
- 0 關(guān)注
- 633 瀏覽
添加回答
舉報(bào)
0/150
提交
取消