型ごとのテーブル継承の使用Landlord
から継承するクラスがあります。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
追加します。たとえば、aは1です。UserProfile
UserProfileId
次に、if (model.AccountType == AccountType.Tenant)
選択したアカウントの種類がTenant
であることがわかります。ユーザーをその役割に追加します。aUserProfileId
は1、aRoleId
は1です。この中if-statement
で、選択した役割はであるため、次のようTenant
に新しいものを作成します。データベースに保存されます( PKとして正しいUserProfileIDを使用)。Tenant
var tenant = db.UserProfile.Create<Tenant>();
問題:1人のユーザーを登録しようとするたびに、2つのUserProfile
エンティティ(2行)がテーブルに追加されます。UserProfile
これはおそらく、私が呼び出しているという事実とWebSecurity.CreateUserAndAccount
、新しいTenant
オブジェクトを作成していることが原因であると理解しています。
この状況を回避するにはどうすればよいですか?
WebSecurity.CreateUserAndAccount
使用しているモデルをUserProfile
テーブルとテーブルに一度追加するにはどうすればよいTenant
ですか?