This is a method for add/update an entity using Self Tracking Entities, what is the equivalent using POCO?
public Hero SaveHero(Hero hero)
{
using (WarEntities model = new WarEntities())
{
if (hero.ChangeTracker.State == ObjectState.Added)
{
model.Heroes.AddObject(hero);
model.SaveChanges();
hero.AcceptChanges();
return hero;
}
else if (hero.ChangeTracker.State == ObjectState.Modified)
{
model.Heroes.ApplyChanges(hero);
model.SaveChanges();
return hero;
}
else
return null;
}
}
The most straightforward way to update an entity is to fetch it by Id, rewrite all the properties and call
SaveChanges():However, you can avoid fetching the entity from the DB by attaching the POCO entity and changing it’s state to
Modified:Note that this method will only work if you already have this “hero” in the DB and are updating the existing entry. You will need a separate method for adding a new “hero”.