在Mvc中使用表格式继承将对象添加到数据库中4 [英] Adding object to database using table-per-type inheritance in Mvc 4

查看:122
本文介绍了在Mvc中使用表格式继承将对象添加到数据库中4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类楼主 UserProfile 继承使用表格型继承。

I have a class Landlord that inherits from UserProfile using table-per-type inheritance.

当新用户在应用程序上注册时,他们输入一些条件,并选择所需的帐户类型,楼主租户

When a new user registers on the application, they enter some criteria and select the type of account they want, either Landlord or Tenant.

这是我的AccountController /注册方式:

Here's my AccountController/Register method:

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);
    }

举个例子,如果我选择了 code>作为注册时所需的帐户类型, WebSecurity.CreateUserAndAccount 会将用户添加到 UserProfile 表中,正确地说,一个 UserProfileId 为1.

As an example, if I selected Tenant as the desired account type when registering, WebSecurity.CreateUserAndAccount would add a user into the UserProfile table, correctly, with say a UserProfileId of 1.

然后,$ code> if(model。 AccountType == AccountType.Tenant)会看到所选帐户类型为租户,将用户添加到该角色,使用 UserProfileId 为1,而 RoleId 为1.在此 if-statement 中,因为选择的角色是租户,我创建一个新的租户如下: var tenant = db .UserProfile.Create< Tenant>(); 并将其保存到数据库(使用正确的UserProfileID作为PK)。

Then, if (model.AccountType == AccountType.Tenant) would see that the selected account type is Tenant, add the user to that role, with a UserProfileId of 1 and a RoleId of 1. Within this if-statement, because selected role is Tenant, I create a new Tenant like so: var tenant = db.UserProfile.Create<Tenant>(); and it is saved to the database (with correct UserProfileID as the PK).

问题:两个 UserProfile 实体(两行)正在每次添加到 UserProfile 表中我尝试注册一个用户。我明白这可能是因为我正在调用 WebSecurity.CreateUserAndAccount 而我正在创建一个新的租户对象

The problem: Two UserProfile entities (two rows) are being added to the UserProfile table each time I try to register ONE user. I understand that this is probably due to the fact that I am calling WebSecurity.CreateUserAndAccount AND I'm creating a new Tenant object.

如何避免这种情况?

如何将 WebSecurity.CreateUserAndAccount into UserProfile table and Tenant table ONCE? / p>

How do I add the model being used in WebSecurity.CreateUserAndAccount into UserProfile table and Tenant table ONCE?

推荐答案

在这种情况下,您不会同时创建UserProfile和租户或房东。一旦创建实体,实体类型不能被更改(甚至将其扩展到子类型)。所以在你的情况下,你只需要跳过创建UserProfile的步骤,只需创建并保存租户或继承它的房东实体。

In this instance you would not create both a UserProfile and a Tenant or Landlord. Once the Entity is created the entity type cannot be changed (even to extend it to a subtype). So in your case, you only need to skip the step of creating the UserProfile and just create and save either the Tenant or the Landlord entity that inherits it.

从我的答案的选项1更多信息链接到此问题:代码第一TPT继承 - 如何提供外键代替EF创建父行我吗?

More info linked from Option 1 of my answer to this question: Code First TPT Inheritance - How can I supply the foreign key instead of EF creating the parent row for me?

这篇关于在Mvc中使用表格式继承将对象添加到数据库中4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆