Is there any method to update an object from a strongly typed object without listing each field ?
Lets consider the following case:
using (var context = new MyDBEntities())
{
var user = (User)Session["EditedUser"];
var oldUser = context.Users.FirstOrDefault(o => o.Id == user.Id);
oldUser.FirstName= user.FirstName;
oldUser.LastName = user.LastName;
etc ....
context.SaveChanges();
}
I have 29 more fields and I am not willing to write them down one by one every time. What I am looking for should be similar to this
using (var context = new MyDBEntities())
{
var user = (User)Session["EditedUser"];
var oldUser = context.Users.FirstOrDefault(o => o.Id == user.Id);
oldUser=user;
context.SaveChanges();
}
Which fails for sure because of the entity's primary key violation. What I would like to achieve here is to update all the fields except the primary key value.
Used the Attach function thanks to 'Silvermind' Now my code looks like this
using (var context = new MyDBEntities())
{
try
{
var user = (User)Session["EditedUser"];
context.Users.Attach(user);
context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
context.SaveChanges();
Session["EditedUser"] = null;
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}
}
I know the accepted answer is seven year old as of this post, so it is likely done a different way now. I found an alternative method that works from this source. One additional note that I found was that you have to then save the object. Here is a full code example in what worked for me. This turned out to be truly priceless as I have performed many work around methods in updating old/ new objects and this makes it a real one stop shop!
EDIT: Modified to match the much simpler format suggested by Gert Arnold
[ResponseType(typeof(Order))]
public IHttpActionResult PutOrder(Order ord)
{
if (!ModelState.IsValid)
{
return Content(HttpStatusCode.BadRequest, "Could not save order, invalid model.");
}
var current = db.Order.Find(ord.OrderId);
try
{
if (current != null)
{
// Update Order in Six Hat to match order in IB
db.Entry(current).CurrentValues.SetValues(ord);
db.SaveChanges();
// TODO: Send Order Change Notifications
}
}
catch(Exception e)
{
return Content(HttpStatusCode.BadRequest, e.Message);
}
return Ok(current);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With