【问题标题】:How do I apply Table-per-type EF4 to create records in sub-tables inheriting from aspnet_Users?如何应用 Table-per-type EF4 在从 aspnetUsers 继承的子表中创建记录?
【发布时间】:2010-11-23 03:07:03
【问题描述】:

从常规的 aspnet_Users 表中,我创建了两个在 UserId 上具有一对一关系的子表。

Table UserClient
-UserId int PK
-ClientNumber int

Table UserEmployee
-UserId int PK
-EmployeeNumber int 

我已经在 edmx 中创建了一个 Table per Type 模型,现在希望在通过成员存储过程创建新的 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”类型取决于它的 RoleId,我目前在查询需要时区分它。现在我希望通过表格来扩展每种类型的属性。

假设新创建的用户是客户。

如何将一条记录插入到 UserClient 表中,它是 aspnet_Users 的 UserId 和这个 ClientNumber?

【问题讨论】:

    标签: asp.net entity-framework-4 table-per-type


    【解决方案1】:

    为现有用户创建客户端的最佳方式是使用存储过程;不是通过映射连接到客户端实体的存储过程,而是可以从代码中显式调用的单独存储过程。
    理想情况下,SP 将 UserId 作为参数,使用该 UserId 将新行插入到 UserClient 表中,然后返回完整的 Client 对象,以便立即使用。

    【讨论】:

    • 没问题,很高兴它有帮助:)
    【解决方案2】:

    创建一个 complimentary 表不是更有意义吗,我们称它为“用户”并将 TPT 应用于该表吗?

    您的“用户”表将具有“aspnet_Users”表(guid 或电子邮件)的 FK。然后让你的两个表派生自 that 表。

    如果您想做特定于身份验证/成员资格的事情,请使用内置的成员资格提供程序 API。

    如果您想做特定于您的域模型的事情,请使用您的 TPH 模型。

    在您上面的示例(“创建模型”方法)中,调用 Membership API 方法:MembershipService.CreateUser(正如您所做的那样),然后如果成功,调用另一个名为 UserDomainService.CreateUser 的方法,它将接受 FK( guid 或电子邮件)为刚刚创建的用户,并将该新用户持久保存到您的 TPH 模型中。

    【讨论】:

    • 谢谢,我现在已经使用了这个方法,并且会检查它作为答案,除了下面关于使用存储过程的答案更接近原始问题的症结。
    • 没问题。只是想我会提供一个替代方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多