默认的MVC5App在IdentityModels.cs中附带了这段代码--这段代码用于默认模板的所有ASP.NET标识操作:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
如果我使用带有实体框架的视图搭建了一个新控制器,并创建了一个"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搭建另一个控制器+视图,例如对于动物模型,这行新代码将在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
。
所以我的问题是:
这两个(ApplicationDbContext
和AllOtherStuffDbContext
)中的哪一个应该用于我自己的所有其他模型?或者我应该只使用默认的自动生成的ApplicationDbContext
,因为它是从基类DbContext
派生的,使用它应该不是问题,或者会有一些开销?你应该在你的应用程序中为你的所有模型只使用一个DbContext
对象(我在哪里读到过这个),所以我甚至不应该考虑在一个应用程序中同时使用ApplicationDbContext
和AllOtherStuffDbContext
?或者,在MVC5中使用ASP.NET Identity的最佳实践是什么?
发布于 2013-11-11 18:30:00
我将使用从IdentityDbContext继承的单个上下文类。这样,您就可以让上下文知道您的类与IdentityDbContext的IdentityUser和角色之间的任何关系。IdentityDbContext中的开销很小,它基本上是一个具有两个DbSets的常规DbContext。一个用于用户,另一个用于角色。
发布于 2013-11-19 00:02:36
如果深入研究IdentityDbContext的抽象,您会发现它看起来就像您的派生DbContext。最简单的方法是Olav的答案,但如果您想要更多地控制正在创建的内容,并减少对身份包have a look at my question and answer here的依赖。如果您使用该链接,这里有一个代码示例,但总的来说,您只需将所需的DbSets添加到您自己的DbContext子类中即可。
https://stackoverflow.com/questions/19902756
复制相似问题