views:

69

answers:

1

I'm migrating from SubSonic to EF4. In SubSonic models had a function called Save, if the key of the model was 0 an insert was done, otherwise an update.

Is there a way to make a generic Save function like in SubSonic? For exmaple using an extension method?

A: 

Yes but you have to do it yourselves. Try something like this:

public interface IEntity
{
  int Id { get; set; }
}

...

public void SaveOrUpdate<T>(T entity) where T : IEntity
{
  using (var context = new MyContext())
  {
    if (entity.Id == 0)
    {
      context.AddObject(entity);
    }
    else
    {
      context.Attach(entity);
      context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
    }

    context.SaveChanges();
  }
}
Ladislav Mrnka