【发布时间】:2013-01-29 20:00:35
【问题描述】:
我有一个类 Landlord,它使用 table-per-type 继承从 UserProfile 继承。
当新用户在应用程序上注册时,他们会输入一些条件并选择他们想要的帐户类型,Landlord 或 Tenant。
这是我的 AccountController/Register 方法:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
new
{
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
AccountType = model.AccountType.ToString()
},
false);
// Add user to role that corresponds with selected account type
if (model.AccountType == AccountType.Tenant)
{
try
{
Roles.AddUserToRole(model.UserName, "Tenant");
using (var db = new LetLordContext())
{
var tenant = db.UserProfile.Create<Tenant>();
tenant.TenantAge = null;
tenant.TenantGroupMembers = null;
tenant.UserId = WebSecurity.CurrentUserId;
tenant.UserName = model.UserName;
// more properties associated with tenant
// ...
db.UserProfile.Add(tenant);
db.SaveChanges();
}
}
catch (ArgumentException e)
{
ModelState.AddModelError("Unable to add user to role", e);
}
}
if (model.AccountType == AccountType.Landlord)
{
try
{
Roles.AddUserToRole(model.UserName, "Landlord");
using (var db = new LetLordContext())
{
var landlord = db.UserProfile.Create<Landlord>();
// same idea as adding a tenant
}
}
catch (ArgumentException e)
{
ModelState.AddModelError("Unable to add user to role", e);
}
}
return RedirectToAction("Confirm", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
例如,如果我在注册时选择 Tenant 作为所需的帐户类型,WebSecurity.CreateUserAndAccount 将正确地将用户添加到 UserProfile 表中,例如 UserProfileId 为 1。
然后,if (model.AccountType == AccountType.Tenant) 将看到所选帐户类型为 Tenant,将用户添加到该角色,UserProfileId 为 1,RoleId 为 1。在此 if-statement 中,因为已选择角色是Tenant,我创建了一个新的Tenant,如下所示:var tenant = db.UserProfile.Create<Tenant>();,并将其保存到数据库中(使用正确的 UserProfileID 作为 PK)。
问题: 每次我尝试注册一个用户时,都会将两个 UserProfile 实体(两行)添加到 UserProfile 表中。我知道这可能是因为我正在调用 WebSecurity.CreateUserAndAccount 并且我正在创建一个新的 Tenant 对象。
如何避免这种情况?
如何将WebSecurity.CreateUserAndAccount 中使用的模型一次添加到UserProfile 表和Tenant 表中?
【问题讨论】:
标签: c# asp.net-mvc database entity-framework