public void Update(T entity) { var manager = SessionManager.Manager; var session = manager.GetSession(manager.Current); SqlConnection conn = null; try { conn = (SqlConnection)session.DbInfo.Connection; using (var command = conn.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = CRUDBase.GetUpdateQuery(table, CanUpdate, IsWhere, (column, isUpdate) => GetValue(entity, column, isUpdate)); command.Transaction = (SqlTransaction)session.DbInfo.Transaction; var rows = command.ExecuteNonQuery(); if (rows == 0) { ThrowConcurrencyException(entity); } entity.SetSystemFields(DateTime.UtcNow, entity.ModifiedBy, entity.Version + 1); } } catch (SqlException e) { throw new Exception("unexpected error updating"); } }
public void Delete(T entity) { var manager = SessionManager.Manager; var session = manager.GetSession(manager.Current); session.GetIdentityMap().Remove(entity.Id); SqlConnection conn = null; var query = string.Empty; try { conn = (SqlConnection)session.DbInfo.Connection; using (var command = conn.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = CRUDBase.GetDeleteQuery(table, (f) => { if (f == SystemColumns.Id) { return(entity.Id.GetSqlSyntax()); } else if (f == SystemColumns.Version) { return(entity.Version.GetSqlSyntax()); } throw new NotSupportedException(); }); command.Transaction = (SqlTransaction)session.DbInfo.Transaction; var records = command.ExecuteNonQuery(); if (records == 0) { ThrowConcurrencyException(entity); } } } catch (SqlException e) { throw new Exception("unexpected error deleting"); } }
public T Find(Guid id) { var manager = SessionManager.Manager; var session = manager.GetSession(manager.Current); var entity = (T)session.GetIdentityMap().Get(id); if (entity == null) { SqlConnection conn = null; try { conn = (SqlConnection)session.DbInfo.Connection; var command = conn.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = CRUDBase.GetLoadQuery(table, () => id.GetSqlSyntax()); var reader = command.ExecuteReader(); if (reader.Read()) { entity = Load(id, reader); string modifiedBy = reader[SystemColumns.ModifiedBy].ToString(); DateTime modified = DateTime.Parse(reader[SystemColumns.Modified].ToString()); int version = int.Parse(reader[SystemColumns.Version].ToString()); entity.SetSystemFields(modified, modifiedBy, version); session.GetIdentityMap().Add(id, entity); } else { throw new Exception(table.Name + " " + id.ToString() + "does not exist"); } } catch (SqlException sqlEx) { throw new Exception("unexpected error finding " + table.Name + " " + id); } } return(entity); }