c# - Separating IdentityUser from UserProfile -
i split user-details it's own table profile foreign key applicationuser, inserts fail.
so got following tables:
aspnetusers { id username passwordhash securitystamp descriminator } and
profiles { id firstname lastname email aspnetuser_id } so changed registerviewmodel adding fields this:
public class registerviewmodel { [required] [display(name = "user name")] public string username { get; set; } [required] [stringlength(100, errormessage = "the {0} must @ least {2} characters long.", minimumlength = 6)] [datatype(datatype.password)] [display(name = "password")] public string password { get; set; } [datatype(datatype.password)] [display(name = "confirm password")] [compare("password", errormessage = "the password , confirmation password not match.")] public string confirmpassword { get; set; } [required] [display(name = "first name")] public string firstname { get; set; } [required] [display(name = "last name")] public string lastname { get; set; } [required] public string email { get; set; } } ... , incorporated fields profiles table register.cshtml , want store information model 2 tables. accountcontroller.register looks this:
// // post: /account/register [httppost] [allowanonymous] [validateantiforgerytoken] public async task<actionresult> register(registerviewmodel model) { if (modelstate.isvalid) { var user = new applicationuser() { username = model.username }; var result = await usermanager.createasync(user, model.password); if (result.succeeded) { var profile = new profile { firstname = model.firstname, lastname = model.lastname, email = model.email, user = user }; var db = new decoupledb(); db.profiles.add(profile); db.savechanges(); await signinasync(user, ispersistent: false); return redirecttoaction("index", "home"); } else { adderrors(result); } } but keep getting error on
db.savechanges(); the error saying im trying violate primary key of aspnetusers table
"violation of primary key constraint 'pk_dbo.aspnetusers'. cannot insert duplicate key in object 'dbo.aspnetusers'. duplicate key value (372775e0-bad5-452f-b65c-cd9bf7b80b34). statement has been terminated."
and cant understand why, because it's foreign key when add profile aspnetuser should not created, or thought.
anyone see fix?
i found answer. have store new user, fetch , populate profile. this:
if (modelstate.isvalid) { var user = new applicationuser {username = model.username}; var result = await usermanager.createasync(user, model.password); if (result.succeeded) { var newuser = db.applicationusers.find(user.id); var profile = new profile { firstname = model.firstname, lastname = model.lastname, email = model.email, identity = newuser, }; db.profiles.add(profile); db.savechanges(); await signinasync(user, ispersistent: false); return redirecttoaction("index", "home"); } else { adderrors(result); } }
Comments
Post a Comment