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(newClientPayment{Type="Credit Card",CardNumber="4111-1111-1111-1111")
Any Help Will Be Appreciate!
Anonymous User
28-Sep-2013Hey Goti!
You should do something like this: