0

i am new in EF. i need to add data if it does not exist in db else update data.i got a code but could not understand how to call it. so need a small example which tell me how could i use AddOrModify to add or update my employee data.

does the below code do the db round trip to check the data exist or not?

how to make the below code extension method?

public void AddOrModify<T>(T entity, string key) where T : class, IEntity
{
     using (var context = new MyContainer())
     {
         if (context.Set<T>().Any(e => e.MyKey == key))
         {
              context.Entry(entity).State = EntityState.Modified;
         } 
         else
         {
              context.Entry(entity).State = EntityState.Added;
         }

         context.SaveChanges();
     }
}

looking for help with sample code.

  • You probably don't want to mark an entity as `Modified`. More likely as `Unchanged` to attach it to a context and start tracking its changes: https://stackoverflow.com/a/39133524/861716. However, you can also use it to set the state to `Modified` if you like. – Gert Arnold Oct 09 '17 at 20:06

1 Answers1

0

By doing so:

public void AddOrModify<T>(this DbSet<T> set, T entity, string key) where T : class, IEntity
{
    ...
}
Orhun
  • 1,162
  • 14
  • 22
  • also show how to call AddOrModify function with small example code if possible please. –  Oct 10 '17 at 14:30