I am trying to create a 'Register New User' feature using entity frame work. Each new user should have one entry in UserAccount table and one in UserProfile. Both are linked by foreign key column UserAccountId. Each new user profile can be approved by an existing admin, so I have a ApprovedById db column(nullable) in UserProfile table
This is what I have done till now.
public class UserAccount
{
[Key] //This is primary key
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserAccountId { get; set; }
[StringLength(320)]
public String LoginEmail { get; set; }
[StringLength(128)]
public String Password { get; set; }
[Column("PasswordExpired")]
public Boolean HasPasswordExpired { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
public class UserProfile
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserProfileId { get; set; }
[StringLength(320)]
public String SecondaryEmail { get; set; }
[StringLength(100)]
public String DisplayName { get; set; }
public int UserAccountId { get; set; }
public virtual UserAccount UserAccount { get; set; }
public int? ApprovedById { get; set; }
public virtual UserAccount ApprovedBy { get; set; }
public DateTime? ApprovedDate { get; set; }
}
public class AccountsDataContext : BaseDataContext<AccountsDataContext> // BaseDataContext has something to get connectionstring etc.
{
public DbSet<UserAccount> UserAccounts { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<UserAccount>()
.HasOptional(a => a.UserProfile)
.WithRequired(p => p.UserAccount);
//I also want to add constraint for ApprovedByAccount here but if I do that it gives me circular dependency error
}
}
public class AccountsModel
{
/// <summary>
/// Password in userAccount will be encrypted before saving.
/// </summary>
public bool CreateNewUser(String primaryEmail, String password, String displayName, out String error)
{
using (AccountsDataContext context = new AccountsDataContext())
{
UserAccount account = new UserAccount { LoginEmail = primaryEmail };
UserProfile profile = new UserProfile { DisplayName = displayName };
if (!context.UserAccounts.Any(a => String.Equals(primaryEmail, a.LoginEmail)))
{
if (profile != null)
account.UserProfile = profile;
account.Password = GetHashString(password);
context.UserAccounts.Add(account);
context.SaveChanges();
error = null;
return true;
}
}
error = "Some error";
return false;
}
}
When I call this last method of Model in following manner
AccountsModel model = new AccountsModel();
string error;
model.CreateNewUser("my@email.com", "password", "The Guy in Problem", out error);
I get exception as
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'UserProfileId'.
So I have two problems
- How to add one to one mapping between Account and Profile
- How to add constraint for ApprovedBy