/// <inheritdoc /> public AllFeatureModel(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { Configuration.LazyLoadingEnabled = true; Configuration.ProxyCreationEnabled = true; System.Data.Entity.Database.SetInitializer <AllFeatureModel>(new AllFeatureModelDatabaseInitializer()); CustomInit(); }
/// <inheritdoc /> public Tripplanner(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { Configuration.LazyLoadingEnabled = true; Configuration.ProxyCreationEnabled = true; System.Data.Entity.Database.SetInitializer <Tripplanner>(new TripplannerDatabaseInitializer()); CustomInit(); }
private bool CommitTransaction(bool b, System.Data.Entity.Core.Objects.SaveOptions saveOptions, DbTransaction transaction, EFDbContext dbContext) { bool result = false; if (transaction == null) { throw new ApplicationException("Cannot commit a transaction while there is no transaction running."); } if (!b) { transaction.Rollback(); } else { try { System.Data.Entity.Core.Objects.ObjectContext objContext = ((IObjectContextAdapter)dbContext).ObjectContext; objContext.SaveChanges(saveOptions); dbContext.SaveChanges(); transaction.Commit(); result = true; } catch (Exception exp) { } finally { ReleaseCurrentTransaction(transaction); } } ReleaseCurrentTransaction(transaction); return(result); }
public bool BulkInsert(List <TEntity> entities, int batchSize) { try { int count = 0; do { var items = entities.Skip(count).Take(batchSize); count += batchSize; // This is optional _context.Configuration.AutoDetectChangesEnabled = false; _context.Set <TEntity>().AddRange(items); _context.SaveChanges(); System.Data.Entity.Core.Objects.ObjectContext objectContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)_context).ObjectContext; //_context.Dispose(); _context = new DbContext(objectContext, false); } while (count < entities.Count); } catch (Exception ex) { throw ex; } return(true); }
public DBChangeTrackerInfo(DbEntityEntry dbEntity, System.Data.Entity.Core.Objects.ObjectContext objContext) { entity = dbEntity.Entity; currentValues = dbEntity.State == System.Data.Entity.EntityState.Deleted ? null : (DbPropertyValues)dbEntity.CurrentValues.Clone(); originalValues = dbEntity.State == System.Data.Entity.EntityState.Added ? null : (DbPropertyValues)dbEntity.OriginalValues.Clone(); state = dbEntity.State; if (entity == null) { return; } #region GetEntityKeyValue string tblN = entity.GetType().Name; System.Data.Entity.Core.EntityKey key = objContext.CreateEntityKey(tblN, entity); DbKeyMember[] km = new DbKeyMember[key.EntityKeyValues.Length]; for (int i = 0; i < key.EntityKeyValues.Length; i++) { km[i] = new DbKeyMember(key.EntityKeyValues[i].Key, key.EntityKeyValues[i].Value); } entityKey = new DbEntityKey(tblN, km); //Tracking changed data if (state == System.Data.Entity.EntityState.Modified && originalValues != null) { listRecordChanged = new List <DbRecordChangedInfo>(); foreach (var fieldProperty in originalValues.PropertyNames) { if (dbEntity.Property(fieldProperty).IsModified) { listRecordChanged.Add(new DbRecordChangedInfo(fieldProperty, originalValues[fieldProperty], currentValues[fieldProperty])); } } } #endregion }
private String GetPropertyNameKey() { System.Data.Entity.Core.Objects.ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; System.Data.Entity.Core.Objects.ObjectSet <T> set = objectContext.CreateObjectSet <T>(); string keyNames = set.EntitySet.ElementType.KeyMembers.Select(k => k.Name).FirstOrDefault(); return(keyNames); }
private string GetKey <K>() where K : class { System.Data.Entity.Core.Objects.ObjectContext objContext = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext; System.Data.Entity.Core.Objects.ObjectSet <K> set = objContext.CreateObjectSet <K>(); string keyName = set.EntitySet.ElementType.KeyMembers.Select(k => k.Name).First().ToString(); return(keyName); }
public GenericRepository(System.Data.Entity.Core.Objects.ObjectContext context) { if (context == null) { throw new ArgumentNullException("context"); } _context = new DbContext(context, true); }
//=============================================================== public static string GetTableName <T>(this System.Data.Entity.Core.Objects.ObjectContext context) where T : class { string sql = context.CreateObjectSet <T>().ToTraceString(); Regex regex = new Regex("FROM (?<table>.*) AS"); Match match = regex.Match(sql); string table = match.Groups["table"].Value; return(table); }
private bool CommitTransaction(System.Data.Entity.Core.Objects.SaveOptions saveOptions, DbTransaction transaction, EFDbContext dbContext) { bool result = false; if (transaction == null) { throw new ApplicationException("Cannot commit a transaction while there is no transaction running."); } try { if (dbContext.ChangeTracker.Entries().Any(x => x.State != System.Data.Entity.EntityState.Detached && x.State != System.Data.Entity.EntityState.Unchanged)) { try { if (BeforeSave != null) { List <object> para = new List <object>(); para.Add(this.UserID); para.Add(dbContext); BeforeSave(para); } System.Data.Entity.Core.Objects.ObjectContext objContext = dbContext.ObjectContext; objContext.SaveChanges(saveOptions); } catch (Exception exp) { if (SaveException != null) { SaveException(exp); } else { throw exp; } } } transaction.Commit(); result = true; } catch (Exception exp) { throw exp; } finally { ReleaseCurrentTransaction(transaction); } return(result); }
protected int SaveChanges(System.Data.Entity.Core.Objects.ObjectContext context) { int i = context.SaveChanges(); if (i == 0) { return(0); } return(1); }
private string GetTableName(Type entityType) { System.Data.Entity.Core.Objects.ObjectContext octx = (this as IObjectContextAdapter).ObjectContext; System.Data.Entity.Core.Metadata.Edm.EntitySetBase et = octx.MetadataWorkspace.GetItemCollection(System.Data.Entity.Core.Metadata.Edm.DataSpace.SSpace) .GetItems <System.Data.Entity.Core.Metadata.Edm.EntityContainer>() .Single() .BaseEntitySets .Where(x => x.Name == entityType.Name) .Single(); //String tableName = String.Concat(et.MetadataProperties["Schema"].Value, ".", et.MetadataProperties["Table"].Value); return(et.MetadataProperties["Table"].Value.ToString()); }
private void BeginTransaction(IsolationLevel level, System.Data.Entity.Core.Objects.ObjectContext objContext, ref DbTransaction transaction) { if (transaction != null) { throw new ApplicationException("Cannot begin a new transaction while an existing transaction is still running. " + "Please commit or rollback the existing transaction before starting a new one."); } if (objContext.Connection.State != ConnectionState.Open) { objContext.Connection.Open(); } transaction = objContext.Connection.BeginTransaction(level); }
protected void Application_Start() { //建立数据库 Database.SetInitializer <PPOBContext>(new PPOBInitializer()); using (var context = new PPOBContext()) { System.Data.Entity.Core.Objects.ObjectContext objcontext = ((IObjectContextAdapter)context).ObjectContext; } AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ModelMetadataProviders.Current = new EnumMetadataProvider(); }
private void SaveChanges(EFDbContext dbContext, System.Data.Entity.Core.Objects.SaveOptions saveOptions, DbTransaction transaction) { if (transaction != null) { throw new ApplicationException("A transaction is running. Call BeginTransaction instead."); } if (dbContext.ChangeTracker.Entries().Any(x => x.State != System.Data.Entity.EntityState.Detached && x.State != System.Data.Entity.EntityState.Unchanged)) { try { if (BeforeSave != null) { List <object> para = new List <object> { this.UserID, dbContext }; BeforeSave(para); } DBTracker tracker = new DBTracker(dbContext); System.Data.Entity.Core.Objects.ObjectContext objContext = dbContext.ObjectContext; objContext.SaveChanges(saveOptions); tracker.SaveChanged(this); } catch (Exception exp) { if (SaveException != null) { SaveException(exp); } else { throw exp; } } } }
public TestDbContext(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { }
public static object GetObjectSet(this System.Data.Entity.Core.Objects.ObjectContext objectContext, System.Type entityType) { }
public SomministrazioneDbContext(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { }
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { System.Data.Entity.Core.Objects.ObjectContext objectContext = (this as IObjectContextAdapter).ObjectContext; objectContext.CommandTimeout = 180; }
/// <summary /> public static void Update <T>(this IQueryable <T> query, Expression <Func <T, T> > obj, QueryOptimizer optimizer, string connectionString) where T : Gravitybox.GeoLocation.EFDAL.IBusinessObject, new() { if (optimizer == null) { optimizer = new QueryOptimizer(); } if (query == null) { throw new Exception("Query must be set"); } //There is nothing to do if (query.ToString().Replace("\r", string.Empty).Split(new char[] { '\n' }).LastOrDefault().Trim() == "WHERE 1 = 0") { return; } var instanceKey = Guid.Empty; System.Data.Entity.Core.Objects.ObjectContext objectContext = null; try { var propContext = query.Provider.GetType().GetProperty("InternalContext"); if (propContext != null) { var context = propContext.GetValue(query.Provider); if (context != null) { var oc = context.GetType().GetProperty("ObjectContext").GetValue(context) as System.Data.Entity.Core.Objects.ObjectContext; objectContext = oc as System.Data.Entity.Core.Objects.ObjectContext; instanceKey = ((IContext)context.GetType().GetProperty("Owner").GetValue(context)).InstanceKey; if (string.IsNullOrEmpty(connectionString)) { var propCs = context.GetType().GetProperty("OriginalConnectionString"); if (propCs != null) { connectionString = (string)propCs.GetValue(context); } } } } if (instanceKey == Guid.Empty) { var context2 = query.Provider.GetType().GetField("_context", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (context2 != null) { var context = context2.GetValue(query.Provider); objectContext = context as System.Data.Entity.Core.Objects.ObjectContext; var qq = objectContext.InterceptionContext.DbContexts.First() as Gravitybox.GeoLocation.EFDAL.IGeoLocationEntities; instanceKey = qq.InstanceKey; if (string.IsNullOrEmpty(connectionString)) { connectionString = Util.StripEFCS2Normal(objectContext.Connection.ConnectionString); } } } if (instanceKey == Guid.Empty) { throw new Exception("Unknown context"); } if (string.IsNullOrEmpty(connectionString)) { var propContext2 = query.GetType().GetProperty("Context"); if (propContext2 != null) { var context = propContext2.GetValue(query) as System.Data.Entity.Core.Objects.ObjectContext; if (context != null) { var builder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(context.Connection.ConnectionString); if (!string.IsNullOrWhiteSpace(builder.ProviderConnectionString)) { objectContext = context; connectionString = builder.ProviderConnectionString; } } } } } catch { } System.Data.Entity.Core.Objects.ObjectParameterCollection existingParams = null; { var objectQuery = query as System.Data.Entity.Core.Objects.ObjectQuery <T>; if (objectQuery == null) { var internalQueryField = query.GetType().GetProperty("InternalQuery", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(query); if (internalQueryField != null) { objectQuery = internalQueryField.GetType().GetProperty("ObjectQuery").GetValue(internalQueryField) as System.Data.Entity.Core.Objects.ObjectQuery <T>; } } if (objectQuery != null) { var ss2 = objectQuery.ToTraceString(); //DO NOT REMOVE! must call this to init params existingParams = objectQuery.GetType().GetProperty("Parameters").GetValue(objectQuery) as System.Data.Entity.Core.Objects.ObjectParameterCollection; } } var startTime = DateTime.Now; var changedList = new Dictionary <string, object>(); #region Parse Tree var propBody = obj.GetType().GetProperty("Body"); if (propBody != null) { var body = propBody.GetValue(obj); if (body != null) { var propBindings = body.GetType().GetProperty("Bindings"); if (propBindings != null) { var members = (IEnumerable <System.Linq.Expressions.MemberBinding>)propBindings.GetValue(body); foreach (System.Linq.Expressions.MemberAssignment item in members) { var name = item.Member.Name; object value = null; if (item.Expression.Type == typeof(int?)) { value = CompileValue <int?>(item.Expression); } else if (item.Expression.Type == typeof(int)) { value = CompileValue <int>(item.Expression); } else if (item.Expression.Type == typeof(string)) { value = CompileValue <string>(item.Expression); } else if (item.Expression.Type == typeof(bool?)) { value = CompileValue <bool?>(item.Expression); } else if (item.Expression.Type == typeof(bool)) { value = CompileValue <bool>(item.Expression); } else if (item.Expression.Type == typeof(byte?)) { value = CompileValue <byte?>(item.Expression); } else if (item.Expression.Type == typeof(byte)) { value = CompileValue <byte>(item.Expression); } else if (item.Expression.Type == typeof(char?)) { value = CompileValue <char?>(item.Expression); } else if (item.Expression.Type == typeof(char)) { value = CompileValue <char>(item.Expression); } else if (item.Expression.Type == typeof(decimal?)) { value = CompileValue <decimal?>(item.Expression); } else if (item.Expression.Type == typeof(decimal)) { value = CompileValue <decimal>(item.Expression); } else if (item.Expression.Type == typeof(double?)) { value = CompileValue <double?>(item.Expression); } else if (item.Expression.Type == typeof(double)) { value = CompileValue <double>(item.Expression); } else if (item.Expression.Type == typeof(float?)) { value = CompileValue <float?>(item.Expression); } else if (item.Expression.Type == typeof(float)) { value = CompileValue <float>(item.Expression); } else if (item.Expression.Type == typeof(long?)) { value = CompileValue <long?>(item.Expression); } else if (item.Expression.Type == typeof(long)) { value = CompileValue <long>(item.Expression); } else if (item.Expression.Type == typeof(short?)) { value = CompileValue <short?>(item.Expression); } else if (item.Expression.Type == typeof(short)) { value = CompileValue <short>(item.Expression); } else if (item.Expression.Type == typeof(DateTime?)) { value = CompileValue <DateTime?>(item.Expression); } else if (item.Expression.Type == typeof(DateTime)) { value = CompileValue <DateTime>(item.Expression); } else if (item.Expression.Type == typeof(Guid?)) { value = CompileValue <Guid?>(item.Expression); } else if (item.Expression.Type == typeof(Guid)) { value = CompileValue <Guid>(item.Expression); } else { throw new Exception("Data type is not handled '" + item.Expression.Type.Name + "'"); } changedList.Add(name, value); } } else { throw new Exception("Update statement must be in format 'm => new Entity { Field = 0 }'"); } } } #endregion //Create a mapping for inheritance var mapping = new List <UpdateSqlMapItem>(); IReadOnlyBusinessObject theObj = new T(); do { var md = theObj.GetMetaData(); mapping.Add(new UpdateSqlMapItem { TableName = md.GetTableName(), FieldList = md.GetFields(), Schema = md.Schema(), Metadata = md }); var newT = md.InheritsFrom(); if (newT == null) { theObj = default(T); } else { theObj = (IReadOnlyBusinessObject)Activator.CreateInstance(newT, false); } } while (theObj != null); var paramIndex = 0; var parameters = new List <System.Data.SqlClient.SqlParameter>(); foreach (var key in changedList.Keys) { var map = mapping.First(x => x.FieldList.Any(z => z == key)); var fieldSql = map.SqlList; var value = changedList[key]; if (value == null) { fieldSql.Add("[" + map.Metadata.GetDatabaseFieldName(key) + "] = NULL"); } else if (value is string) { fieldSql.Add("[" + map.Metadata.GetDatabaseFieldName(key) + "] = @param" + paramIndex); parameters.Add(new System.Data.SqlClient.SqlParameter { ParameterName = "@param" + paramIndex, DbType = System.Data.DbType.String, Value = changedList[key] }); } else if (value is DateTime) { fieldSql.Add("[" + map.Metadata.GetDatabaseFieldName(key) + "] = @param" + paramIndex); parameters.Add(new System.Data.SqlClient.SqlParameter { ParameterName = "@param" + paramIndex, DbType = System.Data.DbType.DateTime, Value = changedList[key] }); } else { fieldSql.Add("[" + map.Metadata.GetDatabaseFieldName(key) + "] = @param" + paramIndex); parameters.Add(new System.Data.SqlClient.SqlParameter { ParameterName = "@param" + paramIndex, Value = changedList[key] }); } paramIndex++; } var sb = new System.Text.StringBuilder(); #region Per table code if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.CanadaPostalCode)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); foreach (var item in mapping.Where(x => x.SqlList.Any()).ToList()) { sb.AppendLine("UPDATE [X] SET"); sb.AppendLine(string.Join(", ", item.SqlList)); sb.AppendLine("FROM [" + item.Schema + "].[" + item.TableName + "] AS [X] INNER JOIN ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.CanadaPostalCode>)query).Select(x => new { x.RowId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[RowId] = [Extent2].[RowId]"); sb.AppendLine("select @@ROWCOUNT"); } } else if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.City)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); foreach (var item in mapping.Where(x => x.SqlList.Any()).ToList()) { sb.AppendLine("UPDATE [X] SET"); sb.AppendLine(string.Join(", ", item.SqlList)); sb.AppendLine("FROM [" + item.Schema + "].[" + item.TableName + "] AS [X] INNER JOIN ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.City>)query).Select(x => new { x.CityId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[CityId] = [Extent2].[CityId]"); sb.AppendLine("select @@ROWCOUNT"); } } else if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.State)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); foreach (var item in mapping.Where(x => x.SqlList.Any()).ToList()) { sb.AppendLine("UPDATE [X] SET"); sb.AppendLine(string.Join(", ", item.SqlList)); sb.AppendLine("FROM [" + item.Schema + "].[" + item.TableName + "] AS [X] INNER JOIN ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.State>)query).Select(x => new { x.StateId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[StateId] = [Extent2].[StateId]"); sb.AppendLine("select @@ROWCOUNT"); } } else if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.Zip)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); foreach (var item in mapping.Where(x => x.SqlList.Any()).ToList()) { sb.AppendLine("UPDATE [X] SET"); sb.AppendLine(string.Join(", ", item.SqlList)); sb.AppendLine("FROM [" + item.Schema + "].[" + item.TableName + "] AS [X] INNER JOIN ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.Zip>)query).Select(x => new { x.ZipId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[ZipId] = [Extent2].[ZipId]"); sb.AppendLine("select @@ROWCOUNT"); } } else { throw new Exception("Entity type not found"); } #endregion if (string.IsNullOrEmpty(connectionString)) { connectionString = GeoLocationEntities.GetConnectionString(); } var newParams = new List <System.Data.SqlClient.SqlParameter>(); if (existingParams != null) { foreach (var ep in existingParams) { newParams.Add(new System.Data.SqlClient.SqlParameter { ParameterName = ep.Name, Value = (ep.Value == null ? System.DBNull.Value : ep.Value) }); } } newParams.AddRange(parameters); QueryPreCache.AddUpdate(instanceKey, sb.ToString(), newParams, optimizer); }
/// <summary> /// Delete all records that match a where condition /// </summary> public static void Delete <T>(this IQueryable <T> query, QueryOptimizer optimizer, string connectionString) where T : Gravitybox.GeoLocation.EFDAL.IBusinessObject, new() { if (optimizer == null) { optimizer = new QueryOptimizer(); } if (query == null) { throw new Exception("Query must be set"); } //There is nothing to do if (query.ToString().Replace("\r", string.Empty).Split(new char[] { '\n' }).LastOrDefault().Trim() == "WHERE 1 = 0") { return; } var instanceKey = Guid.Empty; System.Data.Entity.Core.Objects.ObjectContext objectContext = null; try { var propContext = query.Provider.GetType().GetProperty("InternalContext"); if (propContext != null) { var context = propContext.GetValue(query.Provider); if (context != null) { var oc = context.GetType().GetProperty("ObjectContext").GetValue(context) as System.Data.Entity.Core.Objects.ObjectContext; objectContext = oc as System.Data.Entity.Core.Objects.ObjectContext; instanceKey = ((IContext)context.GetType().GetProperty("Owner").GetValue(context)).InstanceKey; if (string.IsNullOrEmpty(connectionString)) { var propCs = context.GetType().GetProperty("OriginalConnectionString"); if (propCs != null) { connectionString = (string)propCs.GetValue(context); } } } } if (instanceKey == Guid.Empty) { var context2 = query.Provider.GetType().GetField("_context", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (context2 != null) { var context = context2.GetValue(query.Provider); objectContext = context as System.Data.Entity.Core.Objects.ObjectContext; var qq = objectContext.InterceptionContext.DbContexts.First() as Gravitybox.GeoLocation.EFDAL.IGeoLocationEntities; if (qq != null) { instanceKey = qq.InstanceKey; } if (string.IsNullOrEmpty(connectionString)) { connectionString = Util.StripEFCS2Normal(objectContext.Connection.ConnectionString); } } } if (instanceKey == Guid.Empty) { throw new Exception("Unknown context"); } if (string.IsNullOrEmpty(connectionString)) { var propContext2 = query.GetType().GetProperty("Context"); if (propContext2 != null) { var context = propContext2.GetValue(query) as System.Data.Entity.Core.Objects.ObjectContext; if (context != null) { var builder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(context.Connection.ConnectionString); if (!string.IsNullOrWhiteSpace(builder.ProviderConnectionString)) { objectContext = context; connectionString = builder.ProviderConnectionString; } } } } } catch { } System.Data.Entity.Core.Objects.ObjectParameterCollection existingParams = null; { var objectQuery = query as System.Data.Entity.Core.Objects.ObjectQuery <T>; if (objectQuery == null) { var internalQueryField = query.GetType().GetProperty("InternalQuery", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(query); if (internalQueryField != null) { objectQuery = internalQueryField.GetType().GetProperty("ObjectQuery").GetValue(internalQueryField) as System.Data.Entity.Core.Objects.ObjectQuery <T>; } } if (objectQuery != null) { var ss2 = objectQuery.ToTraceString(); //DO NOT REMOVE! must call this to init params existingParams = objectQuery.GetType().GetProperty("Parameters").GetValue(objectQuery) as System.Data.Entity.Core.Objects.ObjectParameterCollection; } } var sb = new System.Text.StringBuilder(); #region Per table code if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.CanadaPostalCode)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); sb.AppendLine("delete [X] from [dbo].[CanadaPostalCode] [X] inner join ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.CanadaPostalCode>)query).Select(x => new { x.RowId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[RowId] = [Extent2].[RowId]"); sb.AppendLine("select @@ROWCOUNT"); } else if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.City)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); sb.AppendLine("delete [X] from [dbo].[City] [X] inner join ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.City>)query).Select(x => new { x.CityId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[CityId] = [Extent2].[CityId]"); sb.AppendLine("select @@ROWCOUNT"); } else if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.State)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); sb.AppendLine("delete [X] from [dbo].[State] [X] inner join ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.State>)query).Select(x => new { x.StateId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[StateId] = [Extent2].[StateId]"); sb.AppendLine("select @@ROWCOUNT"); } else if (typeof(T) == typeof(Gravitybox.GeoLocation.EFDAL.Entity.Zip)) { sb.AppendLine("set rowcount " + optimizer.ChunkSize + ";"); sb.AppendLine("delete [X] from [dbo].[Zip] [X] inner join ("); sb.AppendLine(((IQueryable <Gravitybox.GeoLocation.EFDAL.Entity.Zip>)query).Select(x => new { x.ZipId }).ToString()); sb.AppendLine(") AS [Extent2]"); sb.AppendLine("on [X].[ZipId] = [Extent2].[ZipId]"); sb.AppendLine("select @@ROWCOUNT"); } else { throw new Exception("Entity type not found"); } #endregion if (string.IsNullOrEmpty(connectionString)) { connectionString = GeoLocationEntities.GetConnectionString(); } var newParams = new List <System.Data.SqlClient.SqlParameter>(); if (existingParams != null) { foreach (var ep in existingParams) { newParams.Add(new System.Data.SqlClient.SqlParameter { ParameterName = ep.Name, Value = (ep.Value == null ? System.DBNull.Value : ep.Value) }); } } QueryPreCache.AddDelete(instanceKey, sb.ToString(), newParams, optimizer); }
protected ContextManager(string databaseNameOrConnectionStringName, string label, System.Data.Entity.Infrastructure.DbCompiledModel model, System.Data.Entity.Core.Objects.ObjectContext context) { }
public static void SetConnectionString(this System.Data.Entity.Core.Objects.ObjectContext objectContext, string connectionString) { }
public virtual object CreateContext(System.Type contextType, string databaseNameOrConnectionStringName, string label, System.Data.Entity.Infrastructure.DbCompiledModel model, System.Data.Entity.Core.Objects.ObjectContext context) { }
public EipDbContext(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { InitializePartial(); }
public TContext CreateContext <TContext>(string databaseNameOrConnectionStringName, string label, System.Data.Entity.Infrastructure.DbCompiledModel model, System.Data.Entity.Core.Objects.ObjectContext context) { }
public MySqlSecurityDbContext(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { }
public static System.Data.Entity.Core.Metadata.Edm.EntitySet GetEntitySet(this System.Data.Entity.Core.Objects.ObjectContext objectContext, System.Type entityType) { }
public static string GetTableName(this System.Data.Entity.Core.Objects.ObjectContext context, System.Type entityType) { }
public override int SaveChanges() { Dictionary <Guid, System.Data.Entity.Core.Objects.ObjectStateEntry> added = new Dictionary <Guid, System.Data.Entity.Core.Objects.ObjectStateEntry>(); string userid = null; string systemid = null; string clientIP = null; if (GetCurrentUserId != null) { userid = GetCurrentUserId(); } if (GetCurrentSystemId != null) { systemid = GetCurrentSystemId(); } if (GetCurrentClientIP != null) { clientIP = GetCurrentClientIP(); } ChangeTracker.DetectChanges(); System.Data.Entity.Core.Objects.ObjectContext ctx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter) this).ObjectContext; List <System.Data.Entity.Core.Objects.ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added | System.Data.Entity.EntityState.Modified | System.Data.Entity.EntityState.Deleted) .ToList(); this.logDebug(string.Format("Founded {0} Entity to Save.", objectStateEntryList.Count)); var doHistorical = true; if (master.framework.Configuration.MasterFramework.Database.Historical.isOFF) { doHistorical = false; } if (doHistorical) { foreach (var item in objectStateEntryList.Select((value, index) => new dto.ForEach <System.Data.Entity.Core.Objects.ObjectStateEntry>() { Index = index, Value = value }).ToList()) { var tableName = item.Value.EntitySet.Name; this.logDebug(string.Format("Checking {0} - {1}", item.Index, tableName)); if (!item.Value.IsRelationship) { var withoutHistorical = item.Value.Entity.GetType().GetCustomAttributes(typeof(WithoutHistorical), true).Length > 0; var withHistorical = item.Value.Entity.GetType().GetCustomAttributes(typeof(WithHistorical), true).Length > 0; if (withoutHistorical) { break; } WithHistorical historicalAtt = null; if (withHistorical) { historicalAtt = item.Value.Entity.GetType().GetCustomAttributes(typeof(WithHistorical), true).FirstOrDefault() as WithHistorical; } var properties = item.Value.Entity.GetType().GetProperties(); switch (item.Value.State) { case System.Data.Entity.EntityState.Added: #region Added { #region Key Attribute { var propertyId = properties.Where(o => o.GetCustomAttributes(typeof(Key), true).Length > 0).ToList(); if (propertyId?.Count > 0) { var property = propertyId.FirstOrDefault(); if (property.PropertyType == typeof(Guid)) { if ((Guid)property.GetValue(item.Value.Entity) == Guid.Empty) { bool setvalue = false; var att = property.GetCustomAttributes(typeof(Key), true).FirstOrDefault() as Key; if (att != null) { setvalue = att.AutoGenerated; } if (setvalue) { property.SetValue(item.Value.Entity, Guid.NewGuid()); } } } } } #endregion #region Created Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(Created), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { var createdAtt = itemProperty.GetCreatedAtt(); switch (createdAtt?.CreatedType) { case Enumerators.CreatedType.User: itemProperty.SetValue(item.Value.Entity, userid); break; case Enumerators.CreatedType.Date: itemProperty.SetValue(item.Value.Entity, DateTime.Now); break; } } } } #endregion #region CreatedOrUpdated Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(CreatedOrUpdated), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { var createdAtt = itemProperty.GetCreatedOrUpdatedAtt(); switch (createdAtt?.CreatedType) { case Enumerators.CreatedOrUpdatedType.User: { System.Type propertyType = itemProperty.GetType(); System.TypeCode propertyTypeCode = Type.GetTypeCode(propertyType); if (itemProperty.PropertyType.IsGenericType && itemProperty.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { propertyTypeCode = Type.GetTypeCode(itemProperty.PropertyType.GetGenericArguments()[0]); } switch (propertyTypeCode) { case TypeCode.Int16: case TypeCode.UInt16: if (!string.IsNullOrWhiteSpace(userid)) { itemProperty.SetValue(item.Value.Entity, short.Parse(userid)); } break; case TypeCode.Int32: case TypeCode.UInt32: if (!string.IsNullOrWhiteSpace(userid)) { itemProperty.SetValue(item.Value.Entity, int.Parse(userid)); } break; case TypeCode.Int64: case TypeCode.UInt64: if (!string.IsNullOrWhiteSpace(userid)) { itemProperty.SetValue(item.Value.Entity, long.Parse(userid)); } break; case TypeCode.String: itemProperty.SetValue(item.Value.Entity, userid); break; } } break; case Enumerators.CreatedOrUpdatedType.Date: itemProperty.SetValue(item.Value.Entity, DateTime.Now); break; } } } } #endregion #region SystemId Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(SystemId), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, systemid); } } } #endregion #region UserIP Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(UserIP), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, clientIP); } } } #endregion if (historicalAtt != null) { added.Add(Guid.NewGuid(), item.Value); } } #endregion break; case System.Data.Entity.EntityState.Deleted: #region Deleted { bool isToInactive = false; #region Historical if (HistoricalDeleted != null && historicalAtt != null) { var key = item.Value.EntityKey.EntityKeyValues.FirstOrDefault(); string keyName = key?.Key; string keyValue = key?.Value.ToString(); dto.HistoricalEvent histEvent = dto.HistoricalEvent.InstanceDelete(item.Value.Entity, tableName, keyName, keyValue); HistoricalDeleted(this, histEvent); } #endregion #region Inactive Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(Inactive), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { item.Value.ChangeState(System.Data.Entity.EntityState.Modified); foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, true); } isToInactive = true; } } #endregion if (isToInactive) { #region UpdateDate Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(Updated), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { var updatedAtt = itemProperty.GetUpdatedAtt(); switch (updatedAtt?.UpdatedType) { case Enumerators.UpdatedType.User: itemProperty.SetValue(item.Value.Entity, userid); break; case Enumerators.UpdatedType.Date: itemProperty.SetValue(item.Value.Entity, DateTime.Now); break; } } } } #endregion #region SystemId Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(SystemId), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, systemid); } } } #endregion #region UserIP Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(UserIP), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, clientIP); } } } #endregion } } #endregion break; case System.Data.Entity.EntityState.Modified: #region Modified { var propertyUpdate = properties.Where(o => o.GetCustomAttributes(typeof(Updated), true).Length > 0).ToList(); var propertyInactive = properties.Where(o => o.GetCustomAttributes(typeof(Inactive), true).Length > 0).ToList(); var propertyCreated = properties.Where(o => o.GetCustomAttributes(typeof(Created), true).Length > 0).ToList(); var propertySystemId = properties.Where(o => o.GetCustomAttributes(typeof(SystemId), true).Length > 0).ToList(); var propertyUserIP = properties.Where(o => o.GetCustomAttributes(typeof(UserIP), true).Length > 0).ToList(); var propertyCreatedOrUpdated = properties.Where(o => o.GetCustomAttributes(typeof(CreatedOrUpdated), true).Length > 0).ToList(); #region Update Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(Updated), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { var updatedAtt = itemProperty.GetUpdatedAtt(); switch (updatedAtt?.UpdatedType) { case Enumerators.UpdatedType.User: itemProperty.SetValue(item.Value.Entity, userid); break; case Enumerators.UpdatedType.Date: itemProperty.SetValue(item.Value.Entity, DateTime.Now); break; } } } } #endregion #region CreatedOrUpdated Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(CreatedOrUpdated), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { var createdAtt = itemProperty.GetCreatedOrUpdatedAtt(); switch (createdAtt?.CreatedType) { case Enumerators.CreatedOrUpdatedType.User: { System.Type propertyType = itemProperty.GetType(); System.TypeCode propertyTypeCode = Type.GetTypeCode(propertyType); if (itemProperty.PropertyType.IsGenericType && itemProperty.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { propertyTypeCode = Type.GetTypeCode(itemProperty.PropertyType.GetGenericArguments()[0]); } switch (propertyTypeCode) { case TypeCode.Int16: case TypeCode.UInt16: if (!string.IsNullOrWhiteSpace(userid)) { itemProperty.SetValue(item.Value.Entity, short.Parse(userid)); } break; case TypeCode.Int32: case TypeCode.UInt32: if (!string.IsNullOrWhiteSpace(userid)) { itemProperty.SetValue(item.Value.Entity, int.Parse(userid)); } break; case TypeCode.Int64: case TypeCode.UInt64: if (!string.IsNullOrWhiteSpace(userid)) { itemProperty.SetValue(item.Value.Entity, long.Parse(userid)); } break; case TypeCode.String: itemProperty.SetValue(item.Value.Entity, userid); break; } } break; case Enumerators.CreatedOrUpdatedType.Date: itemProperty.SetValue(item.Value.Entity, DateTime.Now); break; } } } } #endregion #region SystemId Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(SystemId), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, systemid); } } } #endregion #region UserIP Attribute { var propertyRegister = properties.Where(o => o.GetCustomAttributes(typeof(UserIP), true).Length > 0).ToList(); if (propertyRegister?.Count > 0) { foreach (var itemProperty in propertyRegister) { itemProperty.SetValue(item.Value.Entity, clientIP); } } } #endregion #region Historical if (HistoricalModified != null && historicalAtt != null) { var key = item.Value.EntityKey.EntityKeyValues.FirstOrDefault(); string keyName = key?.Key; string keyValue = key?.Value.ToString(); switch (historicalAtt.HistoricalType) { case Enumerators.HistoricalType.ByProperty: { foreach (string propertyName in item.Value.GetModifiedProperties()) { if (propertyUpdate.Any(o => o.Name.ToLower() == propertyName.ToLower()) || propertyInactive.Any(o => o.Name.ToLower() == propertyName.ToLower()) || propertyCreated.Any(o => o.Name.ToLower() == propertyName.ToLower()) || propertySystemId.Any(o => o.Name.ToLower() == propertyName.ToLower()) || propertyCreatedOrUpdated.Any(o => o.Name.ToLower() == propertyName.ToLower()) || propertyUserIP.Any(o => o.Name.ToLower() == propertyName.ToLower())) { continue; } System.Data.Common.DbDataRecord original = item.Value.OriginalValues; string oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString(); System.Data.Entity.Core.Objects.CurrentValueRecord current = item.Value.CurrentValues; string newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString(); if (oldValue != newValue) // probably not necessary { dto.HistoricalEvent histEvent = dto.HistoricalEvent.InstanceChanged(item.Value.Entity, tableName, keyName, keyValue, propertyName, oldValue, newValue); HistoricalModified(this, histEvent); } } } break; case Enumerators.HistoricalType.ByObject: { dto.HistoricalEvent histEvent = dto.HistoricalEvent.InstanceChanged(item.Value.Entity, tableName, keyName, keyValue, string.Empty, string.Empty, string.Empty); HistoricalModified(this, histEvent); } break; } } #endregion } #endregion break; } } } } var ret = base.SaveChanges(); #region Historical Created if (doHistorical) { if (HistoricalCreated != null) { foreach (KeyValuePair <Guid, System.Data.Entity.Core.Objects.ObjectStateEntry> item in added) { var key = item.Value.EntityKey.EntityKeyValues.FirstOrDefault(); string keyName = key?.Key; string keyValue = key?.Value.ToString(); dto.HistoricalEvent histEvent = dto.HistoricalEvent.InstanceAdd(item.Value.Entity, item.Value.EntitySet.Name, keyName, keyValue); HistoricalCreated(this, histEvent); } } } #endregion return(ret); }