public void DetachAll() { foreach (var entry in context.ChangeTracker.Entries().ToList()) { context.Entry(entry.Entity).State = EntityState.Detached; } }
public static void UpdateAllPropertiesToValue <TEntity, TEntityValue>(this ICustomContext context, TEntity entity, string propertyName, TEntityValue value) where TEntity : class { if (entity.GetType().GetProperty(propertyName) != null) { var propertyType = entity.GetType().GetProperty(propertyName).PropertyType; propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType; if (propertyType != value.GetType()) { throw new InvalidCastException($"The type doesn't match the property that is being inserted for {entity.GetType()} - {propertyName}. {propertyType.ToString()} != {value.GetType().ToString()}"); } entity.GetType().GetProperty(propertyName).SetValue(entity, value); if (context.Entry(entity).State != EntityState.Detached) { context.Entry(entity).Property(propertyName).IsModified = true; } } foreach (var property in entity.GetType().GetProperties()) { if (property.PropertyType.IsClass && property.PropertyType.IsByRef) { UpdateAllPropertiesToValue(context, property, propertyName, value); } if (property.PropertyType.IsInterface && property.PropertyType.GetInterface(typeof(IEnumerable <>).FullName) != null) { var propValue = entity.GetType().GetProperty(property.Name).GetValue(entity); if (propValue == null) { continue; } foreach (var propValueCollectionItem in (System.Collections.IEnumerable)propValue) { UpdateAllPropertiesToValue(context, propValueCollectionItem, propertyName, value); } } } }
public static void SetFieldsAsNotModified <TEntity>(this ICustomContext context, TEntity entity, string[] excludedProperties = null) where TEntity : class { foreach (var property in entity.GetType().GetProperties()) { if ((property.PropertyType.IsClass || property.PropertyType.IsPrimitive || property.PropertyType.IsValueType) && excludedProperties.Contains(property.Name)) { context.Entry(entity).Property(property.Name).IsModified = false; } else if (property.PropertyType.IsInterface && property.PropertyType.GetInterface(typeof(IEnumerable <>).FullName) != null) { var propValue = entity.GetType().GetProperty(property.Name).GetValue(entity); if (propValue == null) { continue; } foreach (var propValueCollectionItem in (System.Collections.IEnumerable)propValue) { SetFieldsAsNotModified(context, propValueCollectionItem); } } } }