Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Committing changes to the database using 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

NAME  AGE PHONE_NUM 
Jim   25  555-555-5555 
Jill  48  555-551-5555

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

Table A

NAME  AGE PHONE_NUM
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

entities.TABlEA.AddObject(TableOBJECT);
entities.SaveChanges();

or for updating data

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

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

Ideas?

like image 320
Dan Avatar asked Oct 18 '11 17:10

Dan


1 Answers

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
        entities.TABLEA.ApplyCurrentValues(TableOBJECT);
    else // INSERT
        entities.TABLEA.AddObject(TableOBJECT);
}
entities.SaveChanges();

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

like image 81
Slauma Avatar answered Oct 02 '22 00:10

Slauma