ENTITY FRAMEWORK 4.0 INSERT/UPDATE

Goti Bandu

Total Post:119

Points:835
Posted by  Goti Bandu
 1131  View(s)
Ratings:
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!

  1. Pravesh Singh

    Post:101

    Points:709
    Re: Entity Framework 4.0 Insert/Update

    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();
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!