C# Asp.Net身份用户管理器和工作单元-如何匹配它们?
我正在使用工作单元模式,并在一个名为MyProject.Domain.DAL.UnitOfWork的单独子项目中为其定义了一个类 不幸的是,整个ASP.NETIdentity基础设施都在我的主项目MyProject中(如教程中所示) 更麻烦的是:据我所知,ASP.NET标识使用自己的DBContext:C# Asp.Net身份用户管理器和工作单元-如何匹配它们?,c#,entity-framework,asp.net-identity,C#,Entity Framework,Asp.net Identity,我正在使用工作单元模式,并在一个名为MyProject.Domain.DAL.UnitOfWork的单独子项目中为其定义了一个类 不幸的是,整个ASP.NETIdentity基础设施都在我的主项目MyProject中(如教程中所示) 更麻烦的是:据我所知,ASP.NET标识使用自己的DBContext: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { /// <summar
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
/// <summary>
/// Initializes a new instance of the <see cref="ApplicationDbContext"/> class, using the EFDB context.
/// </summary>
public ApplicationDbContext()
: base("EFDBContext", throwIfV1Schema: false)
{
}
/// <summary>
/// Creates this instance.
/// </summary>
/// <returns>A database context</returns>
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
调用代码示例:
public class IndexController : Controller
{
// uow and userManager are instantiated through Ninject
// example code, normally this would be properties of the controller
public ActionResult Create(IUnitOfWork uow, ApplicationUserManager userManager, int someID )
{
Project newProject = new Project();
ApplicationUser user = await UserManager.FindByIdAsync(someID);
// this should give a conflict, since two different DataContexts are involved
newProject.User = user;
uow.Projects.Insert(newProject);
uow.Save()
return this.View();
}
}
}模板有点混乱。您不应该创建单独的
DbContext
,而应该使用数据模型的其余部分扩展现有的ApplicationDbContext
。只要在IdentityConfig.cs
中更改类型,就可以将其移动到项目中的其他位置
但是,在使用工作单元时,有一个更难解决的问题,那就是ASP.NET标识方法在内部调用
SaveChanges()
,而在使用工作单元时,通常只希望在所有工作完成后调用。一种解决方法是使用TransactionScope()
,但在ASP.NET Identity使用的每个请求DbContext之前创建它可能会很麻烦。关于DbContext的建议很好,我刚才还在挣扎。。。。另一个问题确实很严重。。。我不知道如何流利地解决这个问题。我真的不喜欢Asp.net身份,充满了半途而废的想法
public class IndexController : Controller
{
// uow and userManager are instantiated through Ninject
// example code, normally this would be properties of the controller
public ActionResult Create(IUnitOfWork uow, ApplicationUserManager userManager, int someID )
{
Project newProject = new Project();
ApplicationUser user = await UserManager.FindByIdAsync(someID);
// this should give a conflict, since two different DataContexts are involved
newProject.User = user;
uow.Projects.Insert(newProject);
uow.Save()
return this.View();
}
}