Reputation: 71
I have a little problem and I need your help with it. I'm using Entity Framework for database handling and I want to update a dataset in this database.
I have an EntityObject with all the changes and want to be able to update this Object with existing Object.
I'm using the following code to update the data:
IQueryable<Competitors> getCompetitor = DatabaseObject.Competitors.Where(SelectOnly => SelectOnly.competitorID == competitorObject.competitorID);
Competitors competitor = getCompetitor.First();
competitor = competitorObject;
DatabaseObject.SaveChanges();
But this deosn't work. How can I update the date in database?
Upvotes: 1
Views: 133
Reputation: 37760
Assuming, that your competitorObject
is of Competitors
type (competitor = competitorObject
), you have to attach it to your context, mark it as modified, and then save changes:
DatabaseObject.Competitors.Attach(competitorObject);
DatabaseObject.Entry(competitorObject).State = EntityState.Modified;
DatabaseObject.SaveChanges();
There's no need to retrieve source object in your case, but without attaching, the context knows nothing about your updated object.
The piece of code, which is marking an object as modified, can be a little different, if you're using ObjectContext
API instead of DbContext
API:
DatabaseObject.ObjectStateManager.GetObjectStateEntry(competitorObject).SetModified();
Upvotes: 2
Reputation: 4793
The only change you need to make to your code to get it to work is update at least one property on the fetched entity. You are updating the reference, not the property values so like this:
IQueryable<Competitors> getCompetitor = DatabaseObject.Competitors.Where(SelectOnly => SelectOnly.competitorID == competitorObject.competitorID);
Competitors competitor = getCompetitor.First();
competitor.Name = competitorObject.Name;
competitor.Contact = competitorObject.Contact;
DatabaseObject.SaveChanges();
Or as Dennis has said you can attach the CompetitorObject
to the context and mark it as modified. Doing it that way will override all the properties of the existing Competitors
record with the values of CompetitorObject
.
Upvotes: 0