EntityReference has an EntityKey property value that does not match the EntityKey for this object
I want to add the user in Users table with Entity Framework.
I added all the references viz.
this.UserRolesReference.EntityKey = new System.Data.EntityKey("KEntities.UserRoles", "UserRoles", roleID);
this.OfficeMasterReference.EntityKey = new System.Data.EntityKey("KEntities.OfficeMaster", "SROCode", SROCode);
this.UserDesignationsReference.EntityKey = new System.Data.EntityKey("KEntities.UserDesignations", "UserDesignations", designationId);
When I do this
context.AddObject(this.GetType().Name.ToString(), this);[ this is object of Users]
it gives me an error
The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object.
The Users table has only relationship with UserRoles , UserDesignations and OfficeMaster
Still in the KModel.edmx file under Users table in the Navigation Properties it shows CustomPermissions, UserLog
CustomPermissio开发者_StackOverflow中文版ns and UserLog have an association with Users but I am not inserting any values into them.
Thank you in advance
In Entity Framework, you are not supposed to change or set RoleID manually, instead you must set the navigation property and RoleID will be correctly updated.
Role adminRole = GetTheAdminRole(); // get instance of Role
User newUser =new User();
context.Users.Add(newUser);
newUser.Role = adminRole;
context.SaveChanges();
加载中,请稍侯......
精彩评论