A
A
Anton Tarara2016-06-30 09:41:04
ASP.NET
Anton Tarara, 2016-06-30 09:41:04

How to create a user on database initialization?

There is such a code

public class BlogDBInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
    {
        protected override async void Seed(ApplicationDbContext context)
        {

            var userManager = HttpContextExtensions.GetOwinContext(HttpContext.Current).GetUserManager<ApplicationUserManager>();
            var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };
            var result = await userManager.CreateAsync(user, "test1test1?");

            Category c1 = context.Categories.Add(new Category { Title = "Физика" });
            Category c2 = context.Categories.Add(new Category { Title = "Химия" });
            Category c3 = context.Categories.Add(new Category { Title = "Политика" });
            context.Posts.Add(new Post
            {
                Title = "Почему наблюдаема информационно-технологическая революция?",
                Text = @"Авторитаризм формирует гносеологический континентально-европейский тип политической культуры, о чем писали такие авторы, как Н.Луман и П.Вирилио. Согласно классификации М.Вебера, социальная стратификация практически представляет собой тоталитарный тип политической культуры. По мнению Бакунина, натуралистическая парадигма верифицирует постиндустриализм. Исходя из данного утверждения, политическое учение Локка интегрирует эмпирический коллапс Советского Союза. Политическая система, согласно традиционным представлениям, формирует функциональный марксизм, о чем будет подробнее сказано ниже. Референдум теоретически ограничивает континентально-европейский тип политической культуры.

Коллапс Советского Союза, несмотря на внешние воздействия, представляет собой функциональный кризис легитимности. Несомненно, правовое государство иллюстрирует онтологический социализм, такого мнения придерживаются многие депутаты Государственной Думы. Коммунизм практически формирует политический процесс в современной России. Правовое государство косвенно. Субъект власти теоретически возможен.

Субъект власти отражает политический процесс в современной России. Постиндустриализм, несмотря на внешние воздействия, традиционно означает референдум, говорится в докладе ОБСЕ. Управление политическими конфликтами, особенно в условиях политической нестабильности, означает тоталитарный тип политической культуры. Элемент политического процесса теоретически сохраняет субъект власти.",
                Category = c2,
                Created_at = DateTime.Now,
                User = user
            });
            base.Seed(context);
        }

    }

When executed, an error occurs
Server error in application '/'.
An asynchronous module or handler exited while the asynchronous operation was still pending.
Description: An unhandled exception occurred while executing the current web request. Check the stack trace for more information about this error and the code snippet that caused it.
Exception Details: System.InvalidOperationException: An asynchronous module or handler terminated while the asynchronous operation was still pending.
Source Error:
An unhandled exception occurred while executing the current web request. Information about the origin and location of the exception can be obtained using the following exception stack trace.
Stack trace:
[InvalidOperationException: An asynchronous module or handler exited while the asynchronous operation was still pending.]
Version Information: Microsoft .NET Framework, version:4.0.30319; ASP.NET Version: 4.6.1073.0

I can't figure out what the problem is, maybe I'm doing something wrong. The task at initialization of basis to enter there the data and zaregat one user.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir S, 2016-06-30
@hePPer

remove from the async and await code, the line var result = await userManager.CreateAsync(user, "test1test1?"); replace with var result = userManager.Create(user, "test1test1?");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question