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?

peter
  • 11
  • 1
  • 3

2 Answers2

8

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
  • 360,892
  • 59
  • 660
  • 670
0

I think a little bit better version will be public static void SaveOrUpdate(this T entity) where T : IEntity