过程中的ASP.NET MVC应用程序中使用的UserManager种子法没有用户已创建过程中、应用程序、用户、种子法

2023-09-03 04:01:03 作者:倾寒

种子方法运行,记录/对象添加到我的数据库。

每一个对象被添加,因为它应该,直到我尝试将用户添加到我的应用程序(在种子方法的底部)。没有人补充说。也有很多 SQL 抛出贴底部例外。他们抛出即使种子方法是空的。

如何将用户添加到实体框架管理的数据库?我下面的斯科特·艾伦的教程中创建我的code。

 保护覆盖无效种子(WebApplication2.Models.ApplicationDbContext上下文){

            System.Diagnostics.Debug.WriteLine(种子开始); //工作原理

            如果(!context.Persons.Any()){
                变种人=新的名单,其中,人物> {
             新的Person {名字=约翰,名字=李四,CellNumber =123-456-789,SecondaryPhoneNumber =98873213,地址=1street 2,出生日期= DateTime.Now.Date,PESEL =312312312 注=恼人的},
             新的Person {名字=安娜,名字=李四,CellNumber =113-456-789,SecondaryPhoneNumber =98873213,地址=1street 2,出生日期= DateTime.Now.Date,PESEL =548555672 注=更讨人喜欢}
            };

                persons.ForEach(人=> context.Persons.AddOrUpdate(人));
                context.SaveChanges();
            }

            如果(!context.Meetings.Any()){
                VAR会议=新的名单,其中,会议> {
                新的会议{PERSONID = 1,身体=会议的身体,日期= DateTime.Now}
            };


                meetings.ForEach(会议=> context.Meetings.AddOrUpdate(会议));
                context.SaveChanges();
            }
            如果(!context.Statuses.Any()){
                VAR状态=新的名单,其中,状态> {
                新状态{名称=OK},
                新状态{名称=NOT_OK}
            };



                statuses.ForEach(状态=> context.Statuses.AddOrUpdate(状态));
                context.SaveChanges();

            }
           //一切至今WORKS
            //用户播种

            如果(!context.Users.Any()){
                System.Diagnostics.Debug.WriteLine(用户SEED);
                尝试 {
                    VAR店=新UserStore< ApplicationUser>(上下文);
                    VAR经理=新的UserManager< ApplicationUser>(店);
                    //为什么不创建用户
                    VAR USER1 =新ApplicationUser {用户名=管理,通过电子邮件=informatyka4444@wp.pl};
                    VAR用户2 =新ApplicationUser {用户名=EMP,通过电子邮件=informatyka4444@wp.pl};
                    manager.Create(用户1,管理员);
                    manager.Create(用户2,EMP);

                    context.SaveChanges();
                }赶上(例外五){System.Diagnostics.Debug.WriteLine(有异常); }
            }


        }
 

编辑:

我添加了一些打印的部分,在那里我添加用户还我发布的一些SQL异常输出。

 如果(!context.Users.Any()){
            System.Diagnostics.Debug.WriteLine(用户SEED);
            尝试 {
                System.Diagnostics.Debug.WriteLine(1);
                VAR店=新UserStore< ApplicationUser>(上下文);
                VAR经理=新的UserManager< ApplicationUser>(店);
                //为什么不创建用户
                System.Diagnostics.Debug.WriteLine(2);
                VAR USER1 =新ApplicationUser {用户名=管理,通过电子邮件=informatyka4444@wp.pl};
                VAR用户2 =新ApplicationUser {用户名=EMP,通过电子邮件=informatyka4444@wp.pl};
                System.Diagnostics.Debug.WriteLine(3);
                manager.Create(用户1,管理员);
                manager.Create(用户2,EMP);
                System.Diagnostics.Debug.WriteLine(4);
                context.SaveChanges();
                System.Diagnostics.Debug.WriteLine(5);
            }赶上(例外五){System.Diagnostics.Debug.WriteLine(有异常); }
            System.Diagnostics.Debug.WriteLine(6);
 
图解ASP.NET MVC 5的第一个应用程序

输出:

  CONSTRCTOR
CONSTRCTOR
第一个机会异常类型'System.Data.SqlClient.SqlException'在System.Data.dll中发生
第一个机会异常类型'System.Data.SqlClient.SqlException'在System.Data.dll中发生
第一个机会异常类型'System.Data.SqlClient.SqlException'在System.Data.dll中发生
第一个机会异常类型的System.Data.Entity.Core.EntityCommandExecutionException在EntityFramework.dll发生
第一个机会异常类型的System.Data.Entity.Core.EntityCommandExecutionException在EntityFramework.dll发生
第一个机会异常类型的System.Data.Entity.Core.EntityCommandExecutionException在EntityFramework.dll发生
第一个机会异常类型的System.Data.Entity.Core.EntityCommandExecutionException在EntityFramework.SqlServer.dll发生
CONSTRCTOR
种子开始
用户SEED
1
2
3
iisex press.exe'(CLR v4.0.30319:/ LM / W 3 SVC / 14 / ROOT-1-130527942456023568):加载'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_pl_b77a5c561934e089\mscorlib.resources.dll'.模块始建无符号。
4
五
6
iisex press.exe'(CLR v4.0.30319:/ LM / W 3 SVC / 14 / ROOT-1-130527942456023568):加载'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Internals.dll'.符号加载。
 

编辑2

下面是构造

Models.IdentityModels.cs

 使用System.Security.Claims;
使用System.Threading.Tasks;
使用Microsoft.AspNet.Identity;
使用Microsoft.AspNet.Identity.EntityFramework;
使用System.Data.Entity的;
使用System.Data.Entity.ModelConfiguration.Conventions;

命名空间WebApplication2.Models {
    //您可以通过添加更多的特性,以你的ApplicationUser类用户添加配置文件数据,请访问http://go.microsoft.com/fwlink/?LinkID=317594,以了解更多信息。
    公共类ApplicationUser:IdentityUser {
        公共异步任务< ClaimsIdentity> GenerateUserIdentityAsync(的UserManager< ApplicationUser>经理){
            //注意authenticationType必须CookieAuthenticationOptions.AuthenticationType定义的匹配
            VAR的UserIdentity =等待manager.CreateIdentityAsync(这一点,DefaultAuthenticationTypes.ApplicationCookie);
            //添加自定义的用户要求在这里
            返回的UserIdentity;
        }
    }

    公共类ApplicationDbContext:IdentityDbContext< ApplicationUser> {
        公共ApplicationDbContext()
            :基地(DefaultConnection,throwIfV1Schema:FALSE){
            System.Diagnostics.Debug.WriteLine(CONSTRCTOR);

        }



        公共DbSet<人>人{获得;组; }
        公共DbSet<会议>会议{获得;组; }
        公共DbSet<状态>状态{获得;组; }
        保护覆盖无效OnModelCreating(DbModelBuilder模型构建器){
            base.OnModelCreating(模型构建器);
            modelBuilder.Conventions.Remove&其中; PluralizingTableNameConvention>();
        }

        公共静态ApplicationDbContext创建(){
            返回新ApplicationDbContext();
        }
    }
}
 

Migrations.Confriguration.cs

 命名空间WebApplication2.Migrations {
    使用Microsoft.AspNet.Identity;
    使用Microsoft.AspNet.Identity.EntityFramework;
    使用系统;
    使用System.Collections.Generic;
    使用System.Data.Entity的;
    使用System.Data.Entity.Migrations;
    使用System.Linq的;
    使用WebApplication2.Models;

    内部密封类配置:DbMigrationsConfiguration< WebApplication2.Models.ApplicationDbContext> {
        公共配置(){
            AutomaticMigrationsEnabled = TRUE;
            ContextKey =WebApplication2.Models.ApplicationDbContext;
        }

        保护覆盖无效的种子(WebApplication2.Models.ApplicationDbContext上下文){
            / *
                        System.Diagnostics.Debug.WriteLine(种子开始);
                        如果(!context.Persons.Any()){
                            变种人=新的名单,其中,人物> {
                         新的Person {名字=约翰,名字=李四,CellNumber =123-456-789,SecondaryPhoneNumber =98873213,地址=1street 2,出生日期= DateTime.Now.Date,PESEL =312312312 注=恼人的},
                         新的Person {名字=安娜,名字=李四,CellNumber =113-456-789,SecondaryPhoneNumber =98873213,地址=1street 2,出生日期= DateTime.Now.Date,PESEL =548555672 注=更讨人喜欢}
                        };

                            persons.ForEach(人=> context.Persons.AddOrUpdate(人));
                            context.SaveChanges();
                        }

                        如果(!context.Meetings.Any()){
                            VAR会议=新的名单,其中,会议> {
                            新的会议{PERSONID = 1,身体=会议的身体,日期= DateTime.Now}
                        };


                            meetings.ForEach(会议=> context.Meetings.AddOrUpdate(会议));
                            context.SaveChanges();
                        }
                        如果(!context.Statuses.Any()){
                            VAR状态=新的名单,其中,状态> {
                            新状态{名称=OK},
                            新状态{名称=NOT_OK}
                        };



                            statuses.ForEach(状态=> context.Statuses.AddOrUpdate(状态));
                            context.SaveChanges();

                        } * /
            //用户播种

            如果(!context.Users.Any()){
                System.Diagnostics.Debug.WriteLine(用户SEED);
                尝试 {
                    System.Diagnostics.Debug.WriteLine(1);
                    VAR店=新UserStore< ApplicationUser>(上下文);
                    VAR经理=新的UserManager< ApplicationUser>(店);
                    //为什么不创建用户
                    System.Diagnostics.Debug.WriteLine(2);
                    VAR USER1 =新ApplicationUser {用户名=管理,通过电子邮件=informatyka4444@wp.pl};
                    VAR用户2 =新ApplicationUser {用户名=EMP,通过电子邮件=informatyka4444@wp.pl};
                    System.Diagnostics.Debug.WriteLine(3);
                    manager.Create(用户1,管理员);
                    manager.Create(用户2,EMP);
                    System.Diagnostics.Debug.WriteLine(4);
                    context.SaveChanges();
                    System.Diagnostics.Debug.WriteLine(5);
                }赶上(例外五){System.Diagnostics.Debug.WriteLine(有异常); }
                System.Diagnostics.Debug.WriteLine(6);
            }


        }
    }
}
 

的Global.asax

 使用系统;
使用System.Collections.Generic;
使用System.Data.Entity的;
使用System.Linq的;
使用的System.Web;
使用System.Web.Mvc;
使用System.Web.Optimization;
使用System.Web.Routing;
使用WebApplication2.Migrations;
使用WebApplication2.Models;


命名空间WebApplication2 {
    公共类MvcApplication:System.Web.HttpApplication {
        保护无效的Application_Start(){
            System.Diagnostics.Debug.WriteLine(的Application_Start);

           Database.SetInitializer(新MigrateDatabaseToLatestVersion< ApplicationDbContext,结构>());
           新ApplicationDbContext()Database.Initialize(真正的);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
 

的Web.config

 < XML版本=1.0编码=UTF-8&GT?;
<! - 
  有关如何配置ASP.NET应用程序的更多信息,请访问:
  http://go.microsoft.com/fwlink/?LinkId=301880
   - >
<结构>
  < configSections>

    <节名称=的EntityFrameworkTYPE =System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection,的EntityFramework,版本= 6.0.0.0,文化=中性公钥= b77a5c561934e089requirePermission =FALSE/>
  <! - 有关实​​体框架配置的详细信息,请访问http://go.microsoft.com/fwlink/?LinkID=237468  - >< / configSections>
  <的ConnectionStrings>
    <添加名称=DefaultConnection的connectionString =数据Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20140711041006.mdf;Initial目录= ASPNET-WebApplication2-20140711041006;集成安全性=真的providerName =System.Data.SqlClient的/>
  < /的ConnectionStrings>
  <的appSettings>
    <添加键=网页:版本值=3.0.0.0/>
    <添加键=网页:启用值=FALSE/>
    <添加键=ClientValidationEnabled值=真/>
    <添加键=UnobtrusiveJavaScriptEnabled值=真/>
  < /的appSettings>
  <的System.Web>
    <身份验证模式=无/>
    <编译调试=真正的targetFramework =4.5.1/>
    <的httpRuntime targetFramework =4.5.1/>
  < /system.web>
  < system.webServer>
    <模块>
      <删除名称=FormsAuthenticationModule/>
    < /模块>
  < /system.webServer>
  <运行>
    < assemblyBinding的xmlns =瓮:架构 - 微软COM:asm.v1>
      < dependentAssembly>
        < assemblyIdentity名=System.Web.Helpers公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-3.0.0.0NEWVERSION =3.0.0.0/>
      < / dependentAssembly>
      < dependentAssembly>
        < assemblyIdentity名=System.Web.Mvc公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-5.1.0.0NEWVERSION =5.1.0.0/>
      < / dependentAssembly>
      < dependentAssembly>
        < assemblyIdentity名=System.Web.Optimization公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-1.1.0.0NEWVERSION =1.1.0.0/>
      < / dependentAssembly>
      < dependentAssembly>
        < assemblyIdentity名=System.Web.WebPages公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =1.0.0.0-3.0.0.0NEWVERSION =3.0.0.0/>
      < / dependentAssembly>
      < dependentAssembly>
        < assemblyIdentity名=WebGrease公钥=31bf3856ad364e35/>
        < bindingRedirect oldVersion =0.0.0.0-1.5.2.14234NEWVERSION =1.5.2.14234/>
      < / dependentAssembly>
    < / assemblyBinding>
  < /运行>
  <的EntityFramework>
   <! - <环境>
     <上下文类型=WebApplication2.Models.ApplicationDbContext,WebApplication2>
        < databaseInitializer TYPE =WebApplication2.Migrations.Configuration,WebApplication2/>
      < /背景>
    &所述; /上下文&GT  - →;
    < defaultConnectionFactory TYPE =System.Data.Entity.Infrastructure.SqlConnectionFactory,的EntityFramework/>
    <供应商>
      <供应商invariantName =System.Data.SqlClient的TYPE =System.Data.Entity.SqlServer.SqlProviderServices,EntityFramework.SqlServer/>
    < /供应商>
  < /的EntityFramework>
< /结构>
 

修改3(partialy解决的问题):这下面做的工作。但是,为什么在MVC 5(用户上述经理)介绍的方式不起作用?

  System.Diagnostics.Debug.WriteLine(前的+ context.Users.Any()!);

            如果(!context.Users.Any()){
                System.Diagnostics.Debug.WriteLine(内部);
                VAR散列器=新PasswordHasher();
                VAR用户=新的名单,其中,ApplicationUser> {
                        新ApplicationUser {用户名=admin的,PasswordHash = hasher.HashPassword(管理员)}
                        };

                users.ForEach(用户=> context.Users.AddOrUpdate(用户));
                context.SaveChanges();
            }
 

当前版本的迁移/ (目录)的/有Configuration.cs 种子方法中:

 命名空间WebApplication2.Migrations {
    使用Microsoft.AspNet.Identity;
    使用系统;
    使用System.Collections.Generic;
    使用System.Data.Entity.Migrations;
    使用System.Data.Entity.Validation;
    使用System.Linq的;
    使用WebApplication2.Models;

    内部密封类配置:DbMigrationsConfiguration< WebApplication2.Models.ApplicationDbContext> {
        公共配置(){
            AutomaticMigrationsEnabled = TRUE;
            ContextKey =WebApplication2.Models.ApplicationDbContext;
        }

        保护覆盖无效的种子(WebApplication2.Models.ApplicationDbContext上下文){

            System.Diagnostics.Debug.WriteLine(种子开始);
            如果(!context.Persons.Any()){
                变种人=新的名单,其中,人物> {
                         新的Person {名字=约翰,名字=李四,CellNumber =123-456-789,SecondaryPhoneNumber =98873213,地址=1street 2,出生日期= DateTime.Now.Date,PESEL =312312312 注=恼人的},
                         新的Person {名字=安娜,名字=李四,CellNumber =113-456-789,SecondaryPhoneNumber =98873213,地址=1street 2,出生日期= DateTime.Now.Date,PESEL =548555672 注=更讨人喜欢}
                        };

                persons.ForEach(人=> context.Persons.AddOrUpdate(人));
                context.SaveChanges();
            }

            如果(!context.Meetings.Any()){
                VAR会议=新的名单,其中,会议> {
                            新的会议{PERSONID = 1,身体=会议的身体,日期= DateTime.Now}
                        };


                meetings.ForEach(会议=> context.Meetings.AddOrUpdate(会议));
                context.SaveChanges();
            }
            如果(!context.Statuses.Any()){
                VAR状态=新的名单,其中,状态> {
                            新状态{名称=OK},
                            新状态{名称=NOT_OK}
                        };



                statuses.ForEach(状态=> context.Statuses.AddOrUpdate(状态));
                context.SaveChanges();

            }
            //用户播种
            System.Diagnostics.Debug.WriteLine(前的+ context.Users.Any()!);



            如果(!context.Users.Any()){
                System.Diagnostics.Debug.WriteLine(内部);
                VAR散列器=新PasswordHasher();
                尝试 {
                    VAR用户=新的名单,其中,ApplicationUser> {
                        新ApplicationUser {PasswordHash = hasher.HashPassword(TestPass44!),电子邮件=informatyka4444@wp.pl,用户名=informatyka4444@wp.pl},
                        新ApplicationUser {PasswordHash = hasher.HashPassword(TestPass44!),电子邮件=informatyka4445@wp.pl,用户名=informatyka4445@wp.pl}
                        };

                    users.ForEach(用户=> context.Users.AddOrUpdate(用户));

                    context.SaveChanges();
                }赶上(DbEntityValidationException E){
                    System.Diagnostics.Debug.WriteLine(EXC:);
                    的foreach(DbEntityValidationResult结果e.EntityValidationErrors){
                        的foreach(DbValidationError在result.ValidationErrors错误){
                            System.Diagnostics.Debug.WriteLine(error.ErrorMessage);
                        }
                    }

                }
            }


        }
    }
}
 

解决方案

您必须从上下文获得当前管理器:

  VAR经理= HttpContext.Current.GetOwinContext()GetUserManager< ApplicationUserManager>();
 

请务必inlude的命名空间这样的:

 使用Microsoft.AspNet.Identity.Owin;
 

使用该经理举例来说,你应该能够正确地创建一个用户。

When the Seedmethod runs, records/objects are added to my database.

Every object is added as it should till I try add users to my application(at the bottom of Seed method). No one is added. Also there is lot of SQL exceptions thrown posted at the bottom. They are thrown even if Seed method is empty.

How to add users to Entity Framework managed database? I created my code following Scott Allen's tutorial.

 protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {

            System.Diagnostics.Debug.WriteLine("Seed started");//IT WORKS

            if (!context.Persons.Any()) {
                var persons = new List<Person> { 
             new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
             new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
            };

                persons.ForEach(person => context.Persons.AddOrUpdate(person));
                context.SaveChanges();
            }

            if (!context.Meetings.Any()) {
                var meetings = new List<Meeting>{
                new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
            };


                meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
                context.SaveChanges();
            }
            if (!context.Statuses.Any()) {
                var statuses = new List<Status> {
                new Status{Name = "OK"},
                new Status {Name = "NOT_OK"}
            };



                statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
                context.SaveChanges();

            }
           //EVERYTHING TILL NOW WORKS
            //Users Seeding

            if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("USER SEED");
                try {
                    var store = new UserStore<ApplicationUser>(context);
                    var manager = new UserManager<ApplicationUser>(store);
                    //why user is not created
                    var user1 = new ApplicationUser { UserName = "admin", Email = "informatyka4444@wp.pl" };
                    var user2 = new ApplicationUser { UserName = "emp", Email = "informatyka4444@wp.pl" };
                    manager.Create(user1, "admin");
                    manager.Create(user2, "emp");

                    context.SaveChanges();
                } catch (Exception e) { System.Diagnostics.Debug.WriteLine("THERE WAS AN EXCEPTION"); }
            }


        }

EDIT:

I added some prints to the section where I add users also I posted output with some SQL exceptions.

if (!context.Users.Any()) {
            System.Diagnostics.Debug.WriteLine("USER SEED");
            try {
                System.Diagnostics.Debug.WriteLine("1");
                var store = new UserStore<ApplicationUser>(context);
                var manager = new UserManager<ApplicationUser>(store);
                //why user is not created
                System.Diagnostics.Debug.WriteLine("2");
                var user1 = new ApplicationUser { UserName = "admin", Email = "informatyka4444@wp.pl" };
                var user2 = new ApplicationUser { UserName = "emp", Email = "informatyka4444@wp.pl" };
                System.Diagnostics.Debug.WriteLine("3");
                manager.Create(user1, "admin");
                manager.Create(user2, "emp");
                System.Diagnostics.Debug.WriteLine("4");
                context.SaveChanges();
                System.Diagnostics.Debug.WriteLine("5");
            } catch (Exception e) { System.Diagnostics.Debug.WriteLine("THERE WAS AN EXCEPTION"); }
            System.Diagnostics.Debug.WriteLine("6");

Output:

CONSTRCTOR
CONSTRCTOR
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
A first chance exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll
A first chance exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll
A first chance exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll
A first chance exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll
CONSTRCTOR
Seed started
USER SEED
1
2
3
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/14/ROOT-1-130527942456023568): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_4.0.0.0_pl_b77a5c561934e089\mscorlib.resources.dll'. Module was built without symbols.
4
5
6
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/14/ROOT-1-130527942456023568): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Internals\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Internals.dll'. Symbols loaded.

EDIT 2

Here is CONSTRUCTOR:

Models.IdentityModels.cs

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace WebApplication2.Models {
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false) {
            System.Diagnostics.Debug.WriteLine("CONSTRCTOR");

        }



        public DbSet<Person> Persons { get; set; }
        public DbSet<Meeting> Meetings { get; set; }
        public DbSet<Status> Statuses { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

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

Migrations.Confriguration.cs

namespace WebApplication2.Migrations {
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext> {
        public Configuration() {
            AutomaticMigrationsEnabled = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {
            /*
                        System.Diagnostics.Debug.WriteLine("Seed started");
                        if (!context.Persons.Any()) {
                            var persons = new List<Person> { 
                         new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
                         new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
                        };

                            persons.ForEach(person => context.Persons.AddOrUpdate(person));
                            context.SaveChanges();
                        }

                        if (!context.Meetings.Any()) {
                            var meetings = new List<Meeting>{
                            new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
                        };


                            meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
                            context.SaveChanges();
                        }
                        if (!context.Statuses.Any()) {
                            var statuses = new List<Status> {
                            new Status{Name = "OK"},
                            new Status {Name = "NOT_OK"}
                        };



                            statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
                            context.SaveChanges();

                        }*/
            //Users Seeding

            if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("USER SEED");
                try {
                    System.Diagnostics.Debug.WriteLine("1");
                    var store = new UserStore<ApplicationUser>(context);
                    var manager = new UserManager<ApplicationUser>(store);
                    //why user is not created
                    System.Diagnostics.Debug.WriteLine("2");
                    var user1 = new ApplicationUser { UserName = "admin", Email = "informatyka4444@wp.pl" };
                    var user2 = new ApplicationUser { UserName = "emp", Email = "informatyka4444@wp.pl" };
                    System.Diagnostics.Debug.WriteLine("3");
                    manager.Create(user1, "admin");
                    manager.Create(user2, "emp");
                    System.Diagnostics.Debug.WriteLine("4");
                    context.SaveChanges();
                    System.Diagnostics.Debug.WriteLine("5");
                } catch (Exception e) { System.Diagnostics.Debug.WriteLine("THERE WAS AN EXCEPTION"); }
                System.Diagnostics.Debug.WriteLine("6");
            }


        }
    }
}

Global.asax

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApplication2.Migrations;
using WebApplication2.Models;


namespace WebApplication2 {
    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            System.Diagnostics.Debug.WriteLine("Application_Start");

           Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
           new ApplicationDbContext().Database.Initialize(true);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20140711041006.mdf;Initial Catalog=aspnet-WebApplication2-20140711041006;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
   <!-- <contexts>
     <context type="WebApplication2.Models.ApplicationDbContext, WebApplication2">
        <databaseInitializer type="WebApplication2.Migrations.Configuration, WebApplication2" />
      </context>
    </contexts>-->
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

EDIT 3(partialy solved problem): This below did the job. But why the way introduced in MVC 5(User Manager above) does not work?

System.Diagnostics.Debug.WriteLine("BEFORE " + !context.Users.Any());

            if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("INSIDE");
                var hasher = new PasswordHasher();
                var users = new List<ApplicationUser> { 
                        new ApplicationUser{UserName = "admin", PasswordHash = hasher.HashPassword("admin")}
                        };

                users.ForEach(user => context.Users.AddOrUpdate(user));
                context.SaveChanges();
            }

Current version of Migrations/(directory)/.Configuration.cs with Seed method inside:

namespace WebApplication2.Migrations {
    using Microsoft.AspNet.Identity;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Validation;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext> {
        public Configuration() {
            AutomaticMigrationsEnabled = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {

            System.Diagnostics.Debug.WriteLine("Seed started");
            if (!context.Persons.Any()) {
                var persons = new List<Person> { 
                         new Person{FirstName = "John", LastName = "Doe", CellNumber = "123-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "312312312", Notes = "Annoying"},
                         new Person{FirstName = "Anna", LastName = "Doe", CellNumber = "113-456-789", SecondaryPhoneNumber = "98873213", Address = "1street 2",BirthDate = DateTime.Now.Date, Pesel = "548555672", Notes = "Less Annoying"}
                        };

                persons.ForEach(person => context.Persons.AddOrUpdate(person));
                context.SaveChanges();
            }

            if (!context.Meetings.Any()) {
                var meetings = new List<Meeting>{
                            new Meeting{PersonId = 1, Body = "Body of meeting", Date = DateTime.Now}
                        };


                meetings.ForEach(meeting => context.Meetings.AddOrUpdate(meeting));
                context.SaveChanges();
            }
            if (!context.Statuses.Any()) {
                var statuses = new List<Status> {
                            new Status{Name = "OK"},
                            new Status {Name = "NOT_OK"}
                        };



                statuses.ForEach(status => context.Statuses.AddOrUpdate(status));
                context.SaveChanges();

            }
            //Users Seeding
            System.Diagnostics.Debug.WriteLine("BEFORE " + !context.Users.Any());



            if (!context.Users.Any()) {
                System.Diagnostics.Debug.WriteLine("INSIDE");
                var hasher = new PasswordHasher();
                try {
                    var users = new List<ApplicationUser> { 
                        new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4444@wp.pl", UserName = "informatyka4444@wp.pl"},
                        new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "informatyka4445@wp.pl", UserName = "informatyka4445@wp.pl"}
                        };

                    users.ForEach(user => context.Users.AddOrUpdate(user));

                    context.SaveChanges();
                } catch (DbEntityValidationException e) {
                    System.Diagnostics.Debug.WriteLine("EXC: ");
                    foreach (DbEntityValidationResult result in e.EntityValidationErrors) {
                        foreach (DbValidationError error in result.ValidationErrors) {
                            System.Diagnostics.Debug.WriteLine(error.ErrorMessage);
                        }
                    }

                }
            }


        }
    }
}

解决方案

You have to get the current manager from the context:

var manager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

Be sure to inlude the namespace for this:

using Microsoft.AspNet.Identity.Owin;

Using this manager instance, you should be able to create a user correctly.