Home > DeveloperSection > Forums > Entity Framework 4.0 Insert/Update
Goti Bandu

Total Post:119

Points:835
Posted on    September-28-2013 4:01 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 876  View(s)
Rate this:
I was hoping there is a way to use the same code to both insert and update.

For example, I insert a new client like the below using the entity framework.

using (var context = new GenWebEntities())
{
  clientObj = new Client();
  var client = new Client
  {
    FirstName = "John",
    LastName = "Smith"
  };
  clientObj = client;
  context.SaveChanges();
}

And If I could use the same code to update the client as well, I would not have to write double the code.

using (var context = new GenWebEntities())
{
  clientObj = context.Clients.Single(c => c.ClientId == 31);
  var client = new Client
  {
    FirstName = "Johnathan", // Updated First Name
    LastName = "Rock" // Updated Last name
  };
  clientObj = client;
  context.SaveChanges();
}

If there is one way to code for both the insert and update, I would love to know how as this method above just inserts a new record.

** UPDATE ** The problem I run into with this solution is I have a one to many relationship.

Example:

I have another table ClientPayment that is one to many. So when I need to update the ClientPayment how do I reference this table for the update?

For the insert I would normaly do:

client.ClientPayments.Add(new ClientPayment { Type = "Credit Card", CardNumber = "4111-1111-1111-1111")

Any Help Will Be Appreciate!



Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    September-28-2013 6:34 AM

Hey Goti!

You should do something like this:

private void SaveAndUpdate(int? ClientId)
{
    using (var context = new GenWebEntities())
    {
        Client client;
        if(ClientId.HasValue)
            client=context.Clients.Single(c => c.ClientId == ClientId.Value);
        else
            client = new Client();
        client.FirstName = "Johnathan";
        client.LastName = "Rock";
        if(!ClientId.HasValue)
            context.Clients.Add(client)
        context.SaveChanges();
    }
}

Don't want to miss updates? Please click the below button!

Follow MindStick