ASp.net身份如何为EF使用相同的dbcontext?

时间:2014-07-22 10:24:52

标签: c# asp.net-mvc entity-framework asp.net-identity

我正在尝试将相同的DbContext用于ASP.NET身份和我的其他工作 - 否则会发生不好的事情。不幸的是,我无法实现这一点 - 我最终使用了两个DbContexts,这会导致双重对象等。

我不确定调试此代码需要什么代码...问我是否错过了什么。

启动:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(PriorityDBContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    }
}

PriorityDBContext

public class PriorityDBContext : ApplicationDbContext
    {
        public PriorityDBContext()
            : base()
        {
        }

// seems to be called twice :(
        public static new ApplicationDbContext Create()
        {
            return new PriorityDBContext() as ApplicationDbContext;
        }

 // snipped my DbSets
    }
}

ApplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("EFDBContext", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

在我的主控制器中:

protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{

    var httpContext = System.Web.HttpContext.Current;
    ApplicationDbContext pbContext httpContext.GetOwinContext().Get<ApplicationDbContext>();

    this.UserManager = httpContext.Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
    this.uoW = new UnitOfWork(pbContext);

    return base.BeginExecuteCore(callback, state);
}

1 个答案:

答案 0 :(得分:0)

好的,没关系 - 错误非常明显,基本上是原始状态剩余的结果。 我的工作单元初始化看起来像这样:

/// </summary>
private PriorityDBContext dbContext = new PriorityDBContext();

public UnitOfWork()
{ 
}

public UnitOfWork(ApplicationDbContext dbContext)
{
    this.dbContext = (PriorityDBContext)ApplicationDbContext;
}

为每个新的工作单元创建了一个新的PriorityDbContext。传递给构造函数的dbContext从未使用过。

现在看起来像这样:

    private PriorityDBContext dbContext = null;

    public UnitOfWork()
    {
        PriorityDBContext dbContext = new PriorityDBContext();
    }

    public UnitOfWork(ApplicationDbContext dbContext)
    {
        this.dbContext = dbContext as PriorityDBContext;
    }

问题解决了;)