c# - Adding entity to Identity model -
i getting error understand error don't know going wrong
the alter table statement conflicted foreign key constraint "fk_dbo.aspnetusers_dbo.companydetails_usercompanyid". conflict occurred in database "pxwhitespiderdev", table "dbo.companydetails", column 'companyid'.
within identitymodel autogenerated when create mvc application
public class applicationuser : identityuser { public async task<claimsidentity> generateuseridentityasync(usermanager<applicationuser> manager) { // note authenticationtype must match 1 defined in cookieauthenticationoptions.authenticationtype var useridentity = await manager.createidentityasync(this, defaultauthenticationtypes.applicationcookie); // add custom user claims here return useridentity; } public int usercompanyid { get; set; } [foreignkey("usercompanyid")] public companydetails company { get; set; } } and here entity trying create
public class companydetails { [key, databasegenerated(databasegeneratedoption.identity)] public int companyid { get; set; } [stringlength(100, errormessage = "the {0} must @ least {2} characters long.", minimumlength = 1)] [display(name = "company name")] public string companyname { get; set; } } and within registerviewmodel class
public class registerviewmodel { [required] [emailaddress] [display(name = "email")] public string email { 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; } public companydetails company { get; set; } } before companyid's same within applicationuser class , companydetails class in had same variable name. thought problem changed variable name within applicationuser class, until tried update database again , found out not case.
when added new companyid property, entity framework needed add new column dbo.aspnetusers table represent it. since column did not exist before , non-nullable, default value needed set in column existing records. int type, default value 0. however, 0 unacceptable foreign key, when entity framework attempts attach constraint, fails.
the easiest way solve problem either 1) remove existing rows dbo.aspnetusers or 2) add column , manually update values actual companydetails ids before attaching foreign key constraint.
alternatively, can make companyid nullable int, allow entity framework null out in database when adding column. foreign key constraints can added columns nulls, should work then. however, means relationship optional. if every user should have related companydetails, find way fix issue.
Comments
Post a Comment