In my application, I have the following code ...
public Boolean SaveUserInformation(UserInfoDTO UserInformation) { return dataManager.SaveUserInfo(new UserInfo() { UserInfoID = UserInformation.UserInfoID.HasValue ? UserInformation.UserInfoID.Value : 0, UserID = UserInformation.UserID, ProxyUsername = UserInformation.ProxyUsername, Email = UserInformation.Email, Status = UserInformation.Status }); }
This code calls the method in the dataManager object, which uses the Entity Framework ...
public Boolean SaveUserInfo(UserInfo userInfo) { try { //Validate data prior to database update if (userInfo.UserID == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with UserID property set to NULL."); } if (userInfo.ProxyUsername == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with ProxyUsername property set to NULL."); } if (userInfo.Email == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with Email property set to NULL."); } if (userInfo.UserInfoID == 0) { //Perform Insert using (PriorityOneEntities entities = new PriorityOneEntities()) { entities.UserInfoes.AddObject(userInfo); entities.SaveChanges(); } } else { //Perform Update using (PriorityOneEntities entities = new PriorityOneEntities()) { entities.Attach(userInfo); entities.SaveChanges(); } } return true; } catch (Exception ex) { //TODO: Log Error return false; } }
Inserting this code works just fine. But when I try to update, I get an error: "An object with a null EntityKey cannot be bound to the context of the object."
This happens on this line of code: entities.Attach (userInfo);
What I'm trying to do is to avoid traveling together to the database in order to select the entry that I later make changes and updates, thereby making two round trips to the database.
Any ideas what is going wrong, or how could I do it better?
Thanks.
c # entity-framework entity-framework-4
jdavis
source share