public void SaveOnDb(AuctionEntity entity, bool upDate = false) { using (var context = new MyDBdContext(_connectionString)) { if (upDate is false) { context.AuctionEntities.Add(entity); try { context.SaveChanges(); } catch (DbUpdateException exception) //da rivedere lol { throw new NameAlreadyInUseException(entity.Description, "booo", exception.InnerException); } } else { try { context.Entry(entity).State = EntityState.Modified; context.SaveChanges(); } catch (DbUpdateException) { throw new InvalidOperationException(); } } } }
public void SaveOnDb(UserEntity entity, bool upDate = false) { using (var contextDb = new MyDBdContext(_connectionString)) { if (upDate is false) { try { contextDb.UserEntities.Add(entity); contextDb.SaveChanges(); } catch (DbUpdateException exception) //da rivedere lol { var sqlException = exception.GetBaseException() as SqlException; if (sqlException.Number == 2627) { throw new NameAlreadyInUseException(entity.Id); } throw new InvalidOperationException(); } } else { try { contextDb.UserEntities.Attach(entity); contextDb.Entry(entity).Collection(au => au.WinnerAuctionEntities).Load(); if (entity.WinnerAuctionId != null) { var auction = contextDb.AuctionEntities.Find(entity.WinnerAuctionId, _mySite); contextDb.Entry(entity).Collection(au => au.WinnerAuctionEntities).CurrentValue.Remove(auction); entity.WinnerAuctionId = null; contextDb.Entry(auction).State = EntityState.Modified; } contextDb.Entry(entity).State = EntityState.Modified; contextDb.SaveChanges(); } catch (DbUpdateException) { throw new InvalidOperationException(); } } } }
public void DeleteEntity(UserEntity entity) { using (var context = new MyDBdContext(_connectionString)) { try { context.UserEntities.Attach(entity); context.UserEntities.Remove(entity); context.SaveChanges(); } catch (DbUpdateException) { throw new InvalidOperationException(); } } }