c# - 如何同步使用 UserManager?

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

这个问题在这里已经有了答案:





How would I run an async Task<T> method synchronously?

(25 个回答)


3个月前关闭。




在我的其中之一 IDatabaseInitializerSeed给我的方法 DbContext我将初始数据插入数据库。除其他外,还有一些用户需要初始化。但据我使用 Microsoft.AspNet.Identity.EntityFramework.UserStoreMicrosoft.AspNet.Identity.UserManager它只有异步方法 DbUpdateConcurrencyException如下:

private static void CreateUser(DbContext context, string[] roles, string userName, string userEmail) {

    // given context is 
    var user = new ApplicationUser { /* ... fields init */  };

    var userStoreAdapter = new ApplicationUserRepository(context);
    var manager = new UserManager<ApplicationUser>(userStoreAdapter);

    // pass the creation to manager by calling it synchronously. See UserManagerExtensions
    manager.Create(user, Domain.Constants.DefaultPassword);
    manager.AddToRoles(user.Id, roles);

    context.SaveChanges(); // throws DbUpdateConcurrencyException. See another approach below.
}

所以问题是是否有办法使用 UserManagerDbContext没有并发问题?

我尝试了以下来自 Optimistic Concurrency Patterns 的方法但这不会创建用户:
bool isSaved = true;
do
{
    try
    {
        context.SaveChanges();
        isSaved = true;
    }
    catch (DbUpdateConcurrencyException ex)
    {
        foreach (var entry in ex.Entries)
        {
            entry.Reload();
        }
        isSaved = false;
    }
} while (!isSaved);

最佳答案

var result = Task.Run(() => {
   /*whatever you want here*/
}).Result;

// Do whatever u want with the result after

关于c# - 如何同步使用 UserManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847368/

相关文章:

c# - 查询GPS坐标

C# 派生类型到泛型列表作为参数

c# - 多次调用时出现“DbContext 已处理错误”

c# - 转换表单 EF4 到 EF5 转换新创建

oauth-2.0 - 使用 Identity Core 颁发不记名 JWT token

c# - SignInManager,它是什么以及如何使用,何时使用?

c# - Dropbox OAuth 签名中有什么内容?

c# - LINQ to Entities 不支持“日期”。仅支持初始化器、实体成员和实体导航属性

.NET Core Entity Framework - 迁移路径 --output-dir

c# - 如何检索电子邮件确认 token 代码?