在给定DbContext
的Seed
方法中的IDatabaseInitializer
中,我将初始数据插入到DB。除此之外,还有一些用户需要初始化。但就我使用Microsoft.AspNet.Identity.EntityFramework.UserStore
与Microsoft.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.
}
所以问题是,如果有一种方法使用UserManager
与DbContext
没有并发问题?
我尝试了乐观并发模式中的以下方法,但没有创建用户:
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
要同步使用UserManager,您需要从System.Threading.Tasks中调用. getawaiter (). getresult ()扩展方法。例如,要使用用户管理器同步获取当前用户:
using System.Threading.Tasks;
var currentUser = _userManager.GetUserAsync(User).GetAwaiter().GetResult();
来自System.Threading.Tasks命名空间的这两个扩展方法获取任务GetUsersAsync()的await并获取结果