Committing changes to the database using Entity Framework c# entity-framework


I have a situation where I pull data from a table by date. If no data is supplied for a given date I create a record using default values and display it all to the user. When the user is done manipulating the data I need to commit the changes.

So my question is how do I handle in Entity Framework submitting a table where there could be both updates and adds that need to be done. This is in C# using MVC3 and Entity Framework.

So here's what the data might look like to start,

Table A

Jim   25  555-555-5555 
Jill  48  555-551-5555

After the users done with the data it could look like this,

Table A

Jim   25  555-555-5555
Jill  28  555-551-5555
Rob   42  555-534-6677

How do I commit these changes? My problem is there are both updates and inserts needed?

I've found some code like this but I don't know if it will work in this case.

For adding rows of data


or for updating data

entities.TABLEA.Attach(entities.TABLEA.Single(t => t.NAME == TableOBJECT.NAME));

Will any of this work or do I need to keep track of whats there and what was added?


10/18/2011 6:34:44 PM

Accepted Answer

More or less you already have the solution. You just need to check if your Single call which tries to load the object from the DB has an result or not (use SingleOrDefault instead). If the result is null you need to insert, otherwise update:

foreach (var TableOBJECT in collectionOfYourTableOBJECTsTheUserWorkedWith)
    var objectInDB = entities.TABLEA
        .SingleOrDefault(t => t.NAME == TableOBJECT.NAME);
    if (objectInDB != null) // UPDATE
    else // INSERT

(I'm assuming that NAME is the primary key property of your TableOBJECT entity.)

10/18/2011 5:46:17 PM

Popular Answer

I think you have to keep track of what is new and what is modified. If you do that, that the two code examples you provided are going to work. A simple workaround which I used is to check if an entity's primary key property is set to anything. If it is set to a value, then that is an updated object, otherwise it's new.

Another solution would be to use Entity Framework's Self Tracking Entities, but I do not think that's the right direction to go in a web application (maybe it is in a distributed WCF app).

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow