public SaveResult InsertOrUpdate(IEnumerable <TDTO> dtos) { try { using (NosCoreContext context = DataAccessHelper.Instance.CreateContext()) { context.ChangeTracker.AutoDetectChangesEnabled = false; DbSet <TEntity> dbset = context.Set <TEntity>(); List <TEntity> entitytoadd = new List <TEntity>(); foreach (TDTO dto in dtos) { TEntity entity = Mapper.Map <TEntity>(dto); object value = PrimaryKey.GetValue(dto, null); TEntity entityfound = null; if (value is object[]) { entityfound = dbset.Find((object[])value); } else { entityfound = dbset.Find(value); } if (entityfound != null) { Mapper.Map(entity, entityfound); context.Entry(entityfound).CurrentValues.SetValues(entity); } if (value == null || entityfound == null) { //add in a temp list in order to avoid find(default(PK)) to find this element before savechanges entitytoadd.Add(entity); } } dbset.AddRange(entitytoadd); context.ChangeTracker.AutoDetectChangesEnabled = true; context.SaveChanges(); return(SaveResult.Saved); } } catch (Exception e) { Logger.Error(e); return(SaveResult.Error); } }
public SaveResult InsertOrUpdate(ref TDTO dto) { try { using (NosCoreContext context = DataAccessHelper.Instance.CreateContext()) { TEntity entity = Mapper.Map <TEntity>(dto); DbSet <TEntity> dbset = context.Set <TEntity>(); object value = PrimaryKey.GetValue(dto, null); TEntity entityfound = null; if (value is object[]) { entityfound = dbset.Find((object[])value); } else { entityfound = dbset.Find(value); } if (entityfound != null) { Mapper.Map(entity, entityfound); context.Entry(entityfound).CurrentValues.SetValues(entity); context.SaveChanges(); } if (value == null || entityfound == null) { dbset.Add(entity); } context.SaveChanges(); dto = Mapper.Map <TDTO>(entity); return(SaveResult.Saved); } } catch (Exception e) { Logger.Error(e); return(SaveResult.Error); } }