在创建具有外键约束的新标识2.0用户时,我正在查看我的实现是否正确/有效。我已经扩展了Identity属性,以包含一个OrganisationId外键,用于与我的组织表的一对多关系。
我的演示应用程序已经设置好,因此每个用户都被分配到一个组织,用于多租户目的。许多用户可以与与其指定组织关联的数据进行交互。
我在帐户控制器中修改了标准的注册帖子方法,就像这样(我的修改包含在#Region标签中):
{ '{"Nom":"toto","Message":"test"}': '' }
我只需执行以下操作:
同样,我只是想知道这是一个好/坏方法,所有反馈都是受欢迎的。
答案 0 :(得分:0)
使用交易会更正确吗?
以下是示例:
在你的情况下:
ApplicationDbContext db = new ApplicationDbContext();
using (var trans = db.Database.BeginTransaction(IsolationLevel.ReadCommitted))
{
try
{
//Check if Organisation already exists
if (model.OrganisationId == null)
{
//Create new Organisation object
Organisation organisation = new Organisation(model.OrganisationName);
//Add new Organisation to db conext
db.Organisation.Add(organisation);
//TODO Implement error above for failed creation of new Organisation
//Save new Organisation to db - Throw error & return if fails
if (await db.SaveChangesAsync() <= 0)
return View(model); //Error Required
//Set new Organisation flag
newOrganisationCreatedFlag = true;
//Set new Organisation Id to User Model
model.OrganisationId = organisation.Id;
}
//Create new User
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, OrganisationId = model.OrganisationId };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// Comment the following line to prevent log in until the user is confirmed.
//await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
// Uncomment to debug locally
// TempData["ViewBagLink"] = callbackUrl;
ViewBag.Message = "Check your email and confirm your account before you can log in.";
//return View("Info");
return View("RegisterConfirmEmailMsg");
//return RedirectToAction("Index", "Home");
}
else
{
trans.Rollback();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine(ex.InnerException);
}
}