public virtual TEntity GetById(int id, bool loadAll) { var entity = GetById(id); if (entity == null) { return(null); } if (loadAll) { // load all related properties (refereneces and collections) var entry = _context.Entry(entity); var references = entry.GetReferences(); var collections = entry.GetCollections(); foreach (var item in references) { entry.Reference(item).Load(); } if (entry.State != EntityState.Added) { //Cannot load collections when entry is in Added state because the FK values are not yet set. They get set when context.SaveChanges() is called. foreach (var item in collections) { if (!entry.Collection(item).IsLoaded) { entry.Collection(item).Load(); } } } } return(entity); }
public void SaveChanges() { try { var addedEntities = new List <IEntity>(); foreach (var entry in _context.ChangeTracker.Entries()) { var e = entry.Entity; var entityType = e.GetType().Name; if (e is IEntity) { var entity = e as IEntity; if (e is ILoggedEntity) { if (entry.State == EntityState.Added) { addedEntities.Add(entity); } else if (entry.State == EntityState.Modified || entry.State == EntityState.Deleted) { var al = new ActivityLog() { EntityId = entity.Id, EntityType = entityType, Date = DateTime.Now, PartnerId = GlobalSettings.LoggedInPartnerId, UserId = GlobalSettings.LoggedInUserId, OperationType = entry.State.ToString(), ClientId = GlobalSettings.LoggedInClientId }; //if (entry.State == EntityState.Modified) // cl.ChangeTrackInfo = GetChangedTrackingInfo(entry); _context.ActivityLogs.Add(al); } } } } _context.SaveChanges(); String EntityName = ""; if (addedEntities.Any()) { foreach (var item in addedEntities) { var e = _context.Entry(item).Entity; EntityName = e.GetType().Name; _context.ActivityLogs.Add(new ActivityLog() { EntityId = item.Id, EntityType = e.GetType().Name, Date = DateTime.Now, PartnerId = GlobalSettings.LoggedInPartnerId, UserId = GlobalSettings.LoggedInUserId, OperationType = EntityState.Added.ToString(), ClientId = GlobalSettings.LoggedInClientId }); } } if (EntityName != "CampaignLog" || EntityName != "CampaignLogXML" || EntityName != "Coupon") { _context.SaveChanges(); } } catch (DbEntityValidationException e) { throw new Exception("Validation Errors", e); } catch (DbException e) { throw new Exception("Validation Errors", e); } catch (Exception e) { throw new Exception("Could not save data", e); } }