Во время метода Seed с использованием UserManager в приложениях ASP .NET MVC не было создано ни одного пользователя.

Когда запускается метод Seed, записи/объекты добавляются в мою базу данных.

Каждый объект добавляется как следует, пока я не попытаюсь добавить пользователей в свое приложение (в нижней части метода Seed). Никто не добавляется. Также внизу размещено множество SQL исключений. Они выбрасываются, даже если метод Seed пуст.

Как добавить пользователей в управляемую базу данных Entity Framework? Я создал свой код, следуя руководству Скотта Аллена.

 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 = "[email protected]" };
                    var user2 = new ApplicationUser { UserName = "emp", Email = "[email protected]" };
                    manager.Create(user1, "admin");
                    manager.Create(user2, "emp");

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


        }

ИЗМЕНИТЬ:

Я добавил несколько отпечатков в раздел, где я добавляю пользователей, а также опубликовал вывод с некоторыми исключениями SQL.

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 = "[email protected]" };
                var user2 = new ApplicationUser { UserName = "emp", Email = "[email protected]" };
                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");

Выход:

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.

РЕДАКТИРОВАТЬ 2

Вот 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.Configuration.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 = "[email protected]" };
                    var user2 = new ApplicationUser { UserName = "emp", Email = "[email protected]" };
                    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>

РЕДАКТИРОВАТЬ 3 (частично решенная проблема): приведенное ниже решение помогло. Но почему способ, представленный в MVC 5 (менеджер пользователей выше), не работает?

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();
            }

Текущая версия Migrations/(каталог)/.Configuration.cs с методом Seed внутри:

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 = "[email protected]", UserName = "[email protected]"},
                        new ApplicationUser{PasswordHash = hasher.HashPassword("TestPass44!"), Email = "[email protected]", UserName = "[email protected]"}
                        };

                    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);
                        }
                    }

                }
            }


        }
    }
}

person Yoda    schedule 17.08.2014    source источник
comment
вы запускали в отладке? каков статус Users.Any?   -  person KrishnaDhungana    schedule 18.08.2014
comment
@KrishnaDhungana System.Diagnostics.Debug.WriteLine("USER SEED"); печатает на консоли, поэтому пользователей нет, и он работает до этого момента.   -  person Yoda    schedule 18.08.2014
comment
@KrishnaDhungana Пожалуйста, посмотрите на редактирование, которое я опубликовал и отредактировал фрагмент кода, который добавляет пользователей. Спасибо за помощь.   -  person Yoda    schedule 18.08.2014
comment
Если вы явно не вызываете Database Initialize, начальный метод не будет выполняться во время выполнения. (в качестве альтернативы, во время разработки вы можете использовать миграции БД в командной строке nuget, чтобы также выполнить метод seed).   -  person Erik Philips    schedule 18.08.2014
comment
Метод @ErikPhilips Seed запускается при запуске. Вот почему я получаю вывод на свою консоль.-> см. править   -  person Yoda    schedule 18.08.2014
comment
@ErikPhilips, но я получаю много исключений, показанных в редактировании OP.   -  person Yoda    schedule 18.08.2014
comment
Если вас беспокоят исключения, вы должны публиковать везде, где находятся ваши CONSTRCTOR операторы отладки.   -  person Erik Philips    schedule 18.08.2014
comment
@ErikPhilips Спасибо. Я разместил в EDIT2 все, что, по моему мнению, может быть полезным. Я не знаю, что вызывает эти исключения. Если я могу помочь, объяснить, добавить что-нибудь, пожалуйста, скажите мне.   -  person Yoda    schedule 18.08.2014
comment
@Yoda Немного глупый вопрос, но на какую базу данных вы смотрите? Только для проверки?   -  person KrishnaDhungana    schedule 18.08.2014
comment
@KrishnaDhungana Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication2-20140711041006.mdf ТАБЛИЦА: AspNetUsers   -  person Yoda    schedule 18.08.2014
comment
@KrishnaDhungana EDIT 3 в OP -> Старый способ добавления пользователей сработал, но в обучающих видеороликах Скотта Аллена (Pluralsight) MVC 5 он сказал, что этот UserManager был представлен недавно ... это не сработало.   -  person Yoda    schedule 18.08.2014
comment
@ Йода, я тоже в замешательстве. Вы включили миграцию через консоль PM. Можете ли вы попробовать обновить через консоль PM и посмотреть, какая разница вы видите?   -  person KrishnaDhungana    schedule 18.08.2014
comment
@KrishnaDhungana Я установил для автоматической миграции значение true в коде, также я несколько раз делал update-database в личке и даже изменил базу данных с этого длинного имени (2 сообщения выше) на AppDb. Я должен идти спать, сейчас 4:31 утра. Спасибо за помощь.   -  person Yoda    schedule 18.08.2014
comment
Закодируйте это здорово, но много, если это вне контекста, я не знаю, в каком классе находится метод seed, я не знаю, частью какого класса является ваш код Edit 3.   -  person Erik Philips    schedule 18.08.2014
comment
Метод @ErikPhilips Seed находится в Migrations.Configuration.cs. Я вставил полное содержимое этого файла в EDIT2. Часть кода в EDIT3 находится в методе Seed и заменила использование UserManager. Я вставляю полный Migrations.Configuration.cs в EDIT4 в текущей версии.   -  person Yoda    schedule 18.08.2014
comment
@ErikPhilips Если я могу помочь, объяснить что-нибудь, пожалуйста, скажите мне. Спасибо.   -  person Yoda    schedule 18.08.2014
comment
Что новенького? Что это было? у меня сейчас такая же проблема   -  person Ella Sharakanski    schedule 04.10.2015


Ответы (1)


Вы должны получить текущего менеджера из контекста:

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

Не забудьте указать пространство имен для этого:

using Microsoft.AspNet.Identity.Owin;

Используя этот экземпляр менеджера, вы сможете правильно создать пользователя.

person Rob Tillie    schedule 08.06.2015