2

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.

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

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.

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).

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.

How do I avoid this situation?

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

MattSull
  • 5,514
  • 5
  • 46
  • 68

2 Answers2

2

Instead of calling WebSecurity.CreateUserAndAccount() and create the UserProfile subclass Tenent or Landlord respectively, which results in a duplicate entry in the UserProfile table, you can just create the subclass (providing also the values for the UserProfile) and then call the method WebSecurity.CreateAccount().

Here is how I solved the problem (my subclass is called Physician):

In AccountModels I added the sublass using table-per-type inheritance:

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Physician> Physicians { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

[Table("Physicians")]
public class Physician : UserProfile
{
    public Guid PhysicianGUID { get; set; }
    public string Name { get; set; }
}

In the AccountController/Register method:

if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                using( UsersContext dbContext = new UsersContext()){
                    dbContext.Physicians.Add(new Physician { UserName = model.UserName, Name = "testDoctor", PhysicianGUID = Guid.NewGuid() });
                    dbContext.SaveChanges();
                }
                WebSecurity.CreateAccount(model.UserName, model.Password);
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }
tina
  • 51
  • 4
1

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.

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?

Community
  • 1
  • 1
Matthew
  • 9,851
  • 4
  • 46
  • 77
  • 1
    That stopped the problem of duplicate rows being added to the UserProfile table, but now there's no entry being added to the webpages_Membership table, I presume that's because what I just did there was comment out WebSecurity.CreateUserAndAccount. Would the correct approach be to check what account type was selected, then based on that create either a Tenant or Landlord and call WebSecurity.CreateUserAndAccount within that check? – MattSull Jan 29 '13 at 20:36
  • 1
    You are right on why they are not being added to the membership table. Could you have it accept an object of Type UserProfile and pass in either your Tenant or Landlord as applicable? I have not worked much with Membership so I don't want to recommend a solution outside my depth. From an EF perspective, anything that does have you creating and saving a UserProfile first will solve your issue. Is `WebSecurity.CreateUserAndAccount` something you override? – Matthew Jan 29 '13 at 20:47
  • I tried overriding WebSecurity.CreateUserAndAccount, but it's an abstract method so I couldn't add-in/take away parameters. I've extended the default UserProfile/Register models that come with the Mvc 4 internet template - when registering an account, the additional properties are added using an (I think) anonymous class/method (see question) - they come from the RegisterModel class. If I were to create a RegisterTenantModel and RegisterLandlordModel, check to see what type of account the user has selected and then pass one of the two models in based on the check it might work - I'll try it. – MattSull Jan 30 '13 at 14:21