当数据库尚不存在且应用程序尝试创建它时抛出异常

时间:2015-07-07 11:55:05

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

仅当没有DB且必须创建时才会发生这种情况。关于如何解决这个问题的任何想法?

“对象引用未设置为对象的实例。”被抛到这里:

public static void InitializeIdentityForEF(ApplicationDbContext db)
        {
            using (var applicationDbContext = new ApplicationDbContext())
            {
                var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); // The exception "Object reference not set to an instance of an object." gets thrown here.

应用程序停在此类的某个位置:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Web.Mvc;
using WebApp.Models;
using WebApp.Services;


namespace WebApp.Razor
{
    public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel>
    {
        /// <summary>
        /// Application DB context
        /// </summary>
        protected ApplicationDbContext ApplicationDbContext { get; set; }

        /// <summary>
        /// User manager - attached to application DB context
        /// </summary>
        protected UserManager<User> UserManager { get; set; }

        public CustomWebViewPage()
        {
            this.ApplicationDbContext = new ApplicationDbContext();
            this.UserManager = new UserManager<User>(new UserStore<User>(this.ApplicationDbContext));
        }

        public User CurrentUser
        {
            get
            {
                var currentUser = this.UserManager.FindById(User.Identity.GetUserId());
                if (currentUser == null)
                {
                    currentUser = new User { Name = "", UserName = "", Email = "", Id = "" };
                }
                return currentUser;
            }
        }
    }
}

0 个答案:

没有答案