public void AddEmployees(Territory territory, List <Employee> employes) { using (VirtualStoreContext context = new VirtualStoreContext()) { //marcamos el territorio para que no reciba cambios context.Entry(territory).State = EntityState.Unchanged; if (territory.Employees == null) { territory.Employees = new List <Employee>(); } //recorremos cada empleado que se quiera asociar employes.ForEach(x => { //el empleado tampoco debe recibir cambios context.Entry(x).State = EntityState.Unchanged; //asociamos a la colecion de empleados del territorio el nuevo item //este si recibira cambios territory.Employees.Add(x); }); context.SaveChanges(); } }
public virtual void Create(T entity, List <Expression <Func <T, object> > > unchangeProp) { // se obtiene la lista de propiedades que deben marcarse con el estado Unchanged List <string> unchangelist = unchangeProp.Select(x => ((MemberExpression)x.Body).Member.Name).ToList(); using (VirtualStoreContext context = new VirtualStoreContext()) { context.Set <T>().Add(entity); if (unchangeProp != null) { // se toma la instancia del objeto que esta asignada a la propiedad // y se asigna el estodo Unchanged foreach (string property in unchangelist) { PropertyInfo propertyInfo = typeof(T).GetProperty(property); var value = propertyInfo.GetValue(entity, null); context.Entry(value).State = EntityState.Unchanged; } } context.SaveChanges(); } }
public void Delete(T entity) { using (VirtualStoreContext context = new VirtualStoreContext()) { context.Entry(entity).State = EntityState.Deleted; context.SaveChanges(); } }
public void Delete(Expression <Func <T, bool> > predicate) { using (VirtualStoreContext context = new VirtualStoreContext()) { var entities = context.Set <T>().Where(predicate).ToList(); entities.ForEach(x => context.Entry(x).State = EntityState.Deleted); context.SaveChanges(); } }