2010-11-23 23 views
1

從常規的aspnet_Users表我創建了兩個子表,在UserId上具有一對一的關係。如何應用Table-per-type EF4在從aspnet_Users繼承的子表中創建記錄?

Table UserClient 
-UserId int PK 
-ClientNumber int 

Table UserEmployee 
-UserId int PK 
-EmployeeNumber int 

我在EDMX創建每種類型模型中的表,現在希望在適當的子表中創建相應的記錄,當我創建通過會員存儲程序的新aspnet_User記錄,如下圖所示:

[HttpPost] 
public ActionResult CreateUser(CreateUserModel model) 
{ 
    if (ModelState.IsValid) 
    { 
    // Attempt to create the user 
    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email); 

     if (createStatus == MembershipCreateStatus.Success) 
      { 
      //now that the aspnet_user record is created... 

      FilingBizEntities db = new FilingBizEntities(); 

      //Get the role chosen for the user from selectlist on the CreateUser page 
      var thisrole = db.aspnet_Role.Where(rn => rn.RoleId == model.RoleId).FirstOrDefault(); 

      //Add the user to the role 
      Roles.AddUserToRole(model.UserName, thisrole.RoleName); 

      return RedirectToAction("Index", "Users"); 
      } 
      else 
      { 
       ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); 
      } 
     } 

     ViewData["PasswordLength"] = MembershipService.MinPasswordLength; 
     return View(model); 
    } 

無論是類型「UserClient」或「UserEmployee」的依賴於它的角色ID,在需要時通過查詢我目前區分。現在我希望通過表擴展每個類型的屬性。

假設新創建的用戶是客戶端。

如何使用aspnet_Users的UserId和此ClientNumber將記錄插入到UserClient表中?

回答

1

爲現有用戶創建客戶端的最佳方法是使用存儲過程;不是通過映射連接到客戶端實體的存儲過程,而是可以通過代碼明確調用的獨立存儲過程。
理想情況下,它將是一個SP,它將UserId作爲參數,使用該UserId將新行插入到UserClient表中,然後返回一個完整的Client對象,以便可以立即使用它。

+0

謝謝,我已經成功地使用了這種方法。 – 2010-11-24 04:05:54

+0

沒問題,很高興它幫助:) – 2010-11-24 04:07:18

1

創建一個免費表是不是更有意義,我們稱之爲「用戶」並將TPT應用於該表?

您的「用戶」表將具有FK到「aspnet_Users」表(guid或電子郵件)。然後從得到你的兩張表表。

如果您想要執行特定於身份驗證/成員資格的事情,請使用內置的成員資格提供程序API。

如果您想要執行特定於您的域模型的事情,請使用您的TPH模型。

在你上面的例子(「創建模型」的方法),調用成員身份API方法:MembershipService.CreateUser(因爲你正在做的),然後如果成功,調用稱爲UserDomainService.CreateUser另一種方法,將接受FK(GUID或電子郵件)爲用戶創建,並將新用戶保存到TPH模型中。

相關問題