I've been at this for a while, and I really cannot figure it out. I'm using EF5, Mvc 4, table-per-type inheritance.
I have classes Tenant and Landlord that inherit from UserProfile. When registering a user selects what account type they want, and based on this selection the details they enter on the form (username, first name, last name, email, account type, password) should be added to UserProfile table. I then want the PK of that table to be added as a foreign key to table that matches the account type they selected, either Tenant or Landlord.
I was trying to achieve the above using this method, but that resulted in the problems described in that question.
I've now created a RegisterTenantModel class, with properties that map to a Tenant, and I'm passing an object of type RegisterTenantModel to the AccountController/Register like so...
// ...
if (tenantModel.AccountType == AccountType.Tenant)
{
using (var db = new LetLordContext())
{
var t = db.UserProfile.Create<Tenant>();
WebSecurity.CreateUserAndAccount(tenantModel.UserName, tenantModel.Password,
t = new Tenant
{
AccountType = tenantModel.AccountType,
DateWantToRentFrom = DateTime.Now,
DateWantToRentTo = DateTime.Now,
DesiredPropertyLocation = "",
Email = tenantModel.Email,
FirstName = tenantModel.FirstName,
UserId = WebSecurity.CurrentUserId,
UserName = WebSecurity.CurrentUserName
// More properties that map to Tenant entity
// ...
},
false);
db.SaveChanges();
...but now I'm getting an error Invalid column name
for each of the column names inside t= new Tenant
.
Has anyone ever had to do something similar? Am I approaching this the right way? Help would be much appreciated.
EDIT
Based on what Antonio Simunovic posted below, I think I've come to realise what the problem is. My WebSecurity.InitializeDatabaseConnection()
goes like this...
WebSecurity.InitializeDatabaseConnection("LetLordContext", "UserProfile",
"UserId", "UserName", autoCreateTables: true);
...so when I call Websecurity.CreatUserAndAccount()
in AccountController/Register
it's writing to the UserProfile table as per the parameters in WebSecurity.InitializeDatabaseConnection()
. Looking at the question linked above, you'll see that, based on the account type selected on the form, either a Tenant or Landlord will be added to the UserProfile table by calling...
var tenant = db.UserProfile.Create<Tenant>();
//...
db.UserProfile.Add(tenant);
db.SaveChanges();
...resulting in duplicate entries being added to the UserProfile table.
I think the solution is to create a new table, and point WebSecurity.InitializeDatabaseConnection()
at it.