private void RefreshAllViews(IObjectContextAdapter objectContextAdapter) { string sql = @" select name as vname into #temp from sysobjects where xtype = 'V' declare my_cursor Cursor for select vname from #temp where vname <> 'database_firewall_rules' open my_cursor declare @Name varchar(1024) fetch next from my_cursor into @Name while (@@Fetch_status <> -1) begin exec sp_refreshview @ViewName = @Name fetch next from my_cursor into @Name end close my_cursor deallocate my_cursor drop table #temp "; objectContextAdapter.ObjectContext.ExecuteStoreCommand(sql); }
private void ApplyPatch(SqlPatch patch, IObjectContextAdapter objectContextAdapter) { var reader = new StringReader(patch.Script); while (true) { var sql = ReadNextStatementFromStream(reader); if (sql == null) { break; } try { objectContextAdapter.ObjectContext.ExecuteStoreCommand(sql); } catch (Exception ex) { var message = ex.Message + " " + patch.Name + " " + sql; var crashEx = new Exception(message, ex); crashEx.Data.Add("RepositoryInitializer.ApplyPatch." + patch.Name, sql); throw crashEx; } } reader.Close(); }
public static TableMapping GetTableMapping(this IObjectContextAdapter context, Type type) { var metadata = context.ObjectContext.MetadataWorkspace; // Get the part of the model that contains info about the actual CLR types var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace)); // Get the entity type from the model that maps to the CLR type var entityType = metadata .GetItems <EntityType>(DataSpace.OSpace) .Single(e => objectItemCollection.GetClrType(e) == type); // Get the entity set that uses this entity type var entitySet = metadata .GetItems <EntityContainer>(DataSpace.CSpace) .Single() .EntitySets .Single(s => s.ElementType.Name == entityType.Name); // Find the mapping between conceptual and storage model for this entity set var mapping = metadata.GetItems <EntityContainerMapping>(DataSpace.CSSpace) .Single() .EntitySetMappings .Single(s => s.EntitySet == entitySet); // Find all properties (column) that are mapped var columns = mapping .EntityTypeMappings.Single() .Fragments.Single() .PropertyMappings .OfType <ScalarPropertyMapping>() .ToList(); return(new TableMapping(columns, entitySet, entityType, mapping)); }
public void Update(Role rol, List <User> lstUsrs) { var existingParent = base.Context.Set <Role>().Where(p => p.Id == rol.Id) .Include(p => p.Users).Include(p => p.FormAccesses).SingleOrDefault(); if (existingParent != null) { // Update parent base.Context.Entry(existingParent).CurrentValues.SetValues(rol); // Delete Old Users foreach (var existingChild in existingParent.Users.ToList()) { IObjectContextAdapter contextAdapter = (IObjectContextAdapter)base.Context; System.Data.Entity.Core.Objects.ObjectStateManager stateManager = contextAdapter. ObjectContext.ObjectStateManager; stateManager.ChangeRelationshipState(existingParent, existingChild, "Users", EntityState.Deleted); } //Add New Users List <User> lstUsers = new List <User>(); foreach (User usr in lstUsrs) { lstUsers.Add((User)base.Context.Set(typeof(User)).Find(usr.Id)); } base.Context.Entry(existingParent).Collection("Users").CurrentValue = lstUsers; base.Context.SaveChanges(); } }
public static bool Exists <TEntity>(this IObjectContextAdapter context) where TEntity : class { var entityName = typeof(TEntity).Name; var workspace = context.ObjectContext.MetadataWorkspace; return(workspace.GetItems <EntityType>(DataSpace.CSpace).Any(e => e.Name == entityName)); }
public static T AttachToOrGet <T>(this IObjectContextAdapter contextAdapter, T entity) where T : class { var context = contextAdapter.ObjectContext; string entitySetName = context.CreateObjectSet <T>().EntitySet.Name; T attachedEntity; ObjectStateEntry entry; // Track whether we need to perform an attach bool attach = false; if (context.ObjectStateManager.TryGetObjectStateEntry(context.CreateEntityKey(entitySetName, entity), out entry)) { // Re-attach if necessary attach = entry.State == EntityState.Detached; // Get the discovered entity to the ref attachedEntity = (T)entry.Entity; } else { attachedEntity = entity; // Attach for the first time attach = true; } if (attach) { context.AttachTo(entitySetName, attachedEntity); } return(attachedEntity); }
public static string EntitySetName <T>(this IObjectContextAdapter contextAdapter, T entity) where T : class { var context = contextAdapter.ObjectContext; return(context.CreateObjectSet <T>().EntitySet.Name); }
internal EntityLoader(DbContext context, TEntity entity) { if (context == null) { throw new ArgumentNullException("context"); } if (entity == null) { throw new ArgumentNullException("entity"); } IObjectContextAdapter adapter = context; var objectContext = adapter.ObjectContext; var workspace = objectContext.MetadataWorkspace; EntityType entityType; if (!workspace.TryGetItem <EntityType>(typeof(TEntity).FullName, DataSpace.OSpace, out entityType)) { const string format = "The entity type {0} is not part of the model for the current context." + " Verify the entity is configured with the context and not a complex type."; string message = String.Format(null, format, typeof(TEntity).Name); throw new InvalidOperationException(message); } this.context = context; this.entity = entity; }
public int EliminarEnfermo(int inscripcion) { ObjectParameter param = new ObjectParameter("INSCRIPCION", inscripcion); IObjectContextAdapter adapter = (IObjectContextAdapter)this; return(adapter.ObjectContext.ExecuteFunction("DELETESTICK", param)); }
private void UpdateDatabase() { using (var ctx = new BonoboGitServerContext()) { IObjectContextAdapter ctxAdapter = ctx; foreach (var item in UpdateScriptRepository.GetScriptsBySqlProviderName(ctx.Database.Connection.GetType().Name)) { if (!string.IsNullOrEmpty(item.Precondition)) { try { var preConditionResult = ctxAdapter.ObjectContext.ExecuteStoreQuery <int>(item.Precondition).Single(); if (preConditionResult == 0) { continue; } } catch (Exception) { // consider failures in pre-conditions as an indication that // store ecommand should be executed } } ctxAdapter.ObjectContext.ExecuteStoreCommand(item.Command); } } }
public static EntityContainer Container(this IObjectContextAdapter context) => context .ObjectContext .MetadataWorkspace .GetItemCollection(DataSpace.CSpace) .GetItems <EntityContainer>() .Single();
protected static void AttachCyclicNavigationProperty(IObjectContextAdapter context, object parent, object child, PropertyInfo navProperty = null) { if (parent == null || child == null) { return; } var parentType = ObjectContext.GetObjectType(parent.GetType()); var childType = ObjectContext.GetObjectType(child.GetType()); var navigationProperties = context.GetNavigationPropertiesForType(childType); PropertyInfo parentNavigationProperty = null; if (navProperty != null) { parentNavigationProperty = navProperty; } else { parentNavigationProperty = navigationProperties .Where(navigation => navigation.TypeUsage.EdmType.Name == parentType.Name) .Select(navigation => childType.GetProperty(navigation.Name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) .FirstOrDefault(); } if (parentNavigationProperty != null) { parentNavigationProperty.SetValue(child, parent, null); } }
private static bool GetLoadedEntityIfAny <TEntity>(this DbContext context, ref TEntity entity) where TEntity : class { ObjectStateEntry entry; IObjectContextAdapter adapter = context as IObjectContextAdapter; bool shouldAttach = false; string entitySetName = context.GetEntitySetName <TEntity>(); EntityKey key = adapter.ObjectContext.CreateEntityKey(entitySetName, entity); if (adapter.ObjectContext.ObjectStateManager. TryGetObjectStateEntry(key, out entry)) { if (entry.State == EntityState.Detached) { //if the entity is already loaded but has been detatched shouldAttach = true; } //if the object originally exist on the context return it entity = (TEntity)entry.Entity; } else { //object does not exist on the context shouldAttach = true; } return(!shouldAttach); }
/// <summary> /// Method to update entity into object context with save changes /// </summary> /// <typeparam name="T">Generic type</typeparam> /// <param name="context">object context</param> /// <param name="entity">entity instance</param> /// <returns>returns boolean instance</returns> public static bool UpdateEntityWithSave <T>(this IObjectContextAdapter context, T entity) where T : class { bool isUpdated = false; object originalItem = default(T); EntityKey key = context.ObjectContext.CreateEntityKey(GetBase <T>(context).Name, entity); if (context.ObjectContext.TryGetObjectByKey(key, out originalItem)) { context.ObjectContext.ApplyCurrentValues(key.EntitySetName, entity); try { var artezireDbContext = context as ArtezireDbContext; artezireDbContext.SaveChanges(); //context.ObjectContext.SaveChanges(); isUpdated = true; } catch (OptimisticConcurrencyException ox) { context.ObjectContext.Refresh(RefreshMode.ClientWins, entity); var artezireDbContext = context as ArtezireDbContext; artezireDbContext.SaveChanges(); //context.ObjectContext.SaveChanges(); isUpdated = true; } catch (Exception ex) { isUpdated = false; } } return(isUpdated); }
public void Update(User usr, int[] lstRol) { var existingParent = base.Context.Set <User>().Where(p => p.Id == usr.Id) .Include(p => p.Roles).SingleOrDefault(); if (existingParent != null) { // Update parent base.Context.Entry(existingParent).CurrentValues.SetValues(usr); // Delete Old children foreach (var existingChild in existingParent.Roles.ToList()) { IObjectContextAdapter contextAdapter = (IObjectContextAdapter)base.Context; System.Data.Entity.Core.Objects.ObjectStateManager stateManager = contextAdapter. ObjectContext.ObjectStateManager; stateManager.ChangeRelationshipState(existingParent, existingChild, "Roles", EntityState.Deleted); } List <Role> lstRoles = new List <Role>(); foreach (int id in lstRol) { lstRoles.Add((Role)base.Context.Set(typeof(Role)).Find(id)); } base.Context.Entry(existingParent).Collection("Roles").CurrentValue = lstRoles; base.Context.SaveChanges(); } }
//public static void LoadProperty<T>(this IObjectContextAdapter context, T entity, Expression<Func<T, object>> selector) where T : class //{ //} ///// <summary> ///// Method to commit save changes into database ///// </summary> ///// <typeparam name="T">Generic type</typeparam> ///// <param name="context">Object context</param> ///// <returns>returns rows affected</returns> //internal static int SaveChanges<T>(this IObjectContextAdapter context) //{ // return context.ObjectContext.SaveChanges(SaveOptions.DetectChangesBeforeSave); //} /// <summary> /// Method to return entity set base from object context entity /// </summary> /// <typeparam name="TEntity">Generic type</typeparam> /// <param name="context">object context</param> /// <returns>returns entity set</returns> private static EntitySetBase GetBase <TEntity>(IObjectContextAdapter context) { EntityContainer container = context.ObjectContext.MetadataWorkspace.GetEntityContainer(context.ObjectContext.DefaultContainerName, DataSpace.CSpace); EntitySetBase entitySet = container.BaseEntitySets.FirstOrDefault(item => item.ElementType.Name.Equals(typeof(TEntity).Name)); return(entitySet); }
protected static object CreateEmptyEntityWithKey(IObjectContextAdapter context, object entity) { var instance = Activator.CreateInstance(entity.GetType()); CopyPrimaryKeyFields(context, entity, instance); return(instance); }
public RepositoryBase(IObjectContextAdapter context, IDbSet <T> dbSet) { DbSet = dbSet; DbContext = context; TableName = new Lazy <string>(() => EFExtensions.GetTableName <T>(DbContext), false); IsDisposed = false; }
static string GetSchema(NorthwindEntities northwindEntities) { IObjectContextAdapter schema = northwindEntities; string sqlSchema = schema.ObjectContext.CreateDatabaseScript(); return(sqlSchema); }
private IEnumerable <EntityType> GetTables(IObjectContextAdapter context) { ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext; MetadataWorkspace workspace = objContext.MetadataWorkspace; IEnumerable <EntityType> tables = workspace.GetItems <EntityType>(DataSpace.SSpace); return(tables); }
private static EntityType EntitySchema <TEntity>(this IObjectContextAdapter context) where TEntity : class { var items = context.ObjectContext.MetadataWorkspace .GetItems <EntityType>(DataSpace.SSpace); var name = typeof(TEntity).Name; return(items.SingleOrDefault(type => type.Name == name)); }
/// <summary> /// Initializes a unit of work object. /// </summary> /// <param name="objectContextAdapter">The object context adapter to bind the unit of work to.</param> public UnitOfWork(IObjectContextAdapter objectContextAdapter) { if (objectContextAdapter == null) { throw new ArgumentNullException("objectContextAdapter"); } ObjectContextAdapter = objectContextAdapter; }
internal static ObjectContext GetObjectContext(this DbContext dbContext) { Contract.Assert(dbContext != null); IObjectContextAdapter objectContextAdapter = dbContext; return(objectContextAdapter.ObjectContext); }
public MultipleResultSetWrapper(DbContext db, string query, IEnumerable <SqlParameter> parameters = null) { _db = db; _Adapter = db; _CommandText = query; _parameters = parameters; _resultSets = new List <Func <DbDataReader, IEnumerable> >(); }
private static IEnumerable <string> GetKeyNames(IObjectContextAdapter context) { var set = context.ObjectContext.CreateObjectSet <TEntity>(); var entitySet = set.EntitySet; var keyNames = entitySet.ElementType.KeyMembers.Select(k => k.Name); return(keyNames); }
/// <summary> /// Получить имя таблицы со схемой для сущности /// </summary> /// <param name="context">Контекст</param> /// <param name="entity">Сущность</param> /// <returns>Имя таблицы</returns> public static TableInfo GetEntityTableNameWithSchema(this IObjectContextAdapter context, Type entity) { var metadata = context.ObjectContext.MetadataWorkspace; var mappingItemCollection = (StorageMappingItemCollection)metadata.GetItemCollection(DataSpace.CSSpace); var storeContainer = ((EntityContainerMapping)mappingItemCollection[0]).StoreEntityContainer; var baseEntitySet = storeContainer.BaseEntitySets.Single(es => es.Name == entity.Name); return(new TableInfo(baseEntitySet.Schema, baseEntitySet.Table)); }
protected static EntityKey CreateEntityKey(IObjectContextAdapter context, object entity) { if (entity == null) { throw new ArgumentNullException("entity"); } return(context.ObjectContext.CreateEntityKey(context.GetEntitySetName(entity.GetType()), entity)); }
private static void CopyPrimaryKeyFields(IObjectContextAdapter context, object from, object to) { var keyProperties = context.GetPrimaryKeyFieldsFor(from.GetType()).ToList(); foreach (var keyProperty in keyProperties) { keyProperty.SetValue(to, keyProperty.GetValue(from, null), null); } }
private string GetEntityName(IObjectContextAdapter context) { var entitySetName = context.ObjectContext .MetadataWorkspace .GetEntityContainer(context.ObjectContext.DefaultContainerName, DataSpace.CSpace) .BaseEntitySets.First(bes => bes.ElementType.Name == typeof(TEntity).Name).Name; return(string.Format("{0}.{1}", context.ObjectContext.DefaultContainerName, entitySetName)); }
static void Main(string[] args) { // This will not complie DbContext ctx = new DbContext("Non existing connection string"); //var context = ctx.ObjectContext; IObjectContextAdapter explicitCtx = ctx; var adapterContext = explicitCtx.ObjectContext; }
public EntityMetaDataProviderEF6(IObjectContextAdapter contextAdapter, Type entityType) { if (null == contextAdapter) throw new ArgumentNullException("IObjectContextAdapter"); if (null == entityType) throw new ArgumentNullException("entityType"); this.contextAdapter = contextAdapter; this.entityType = entityType; }
private static IEntityMetaData FromEdmx(IObjectContextAdapter contextAdapter, Type entityType) { List<SchemaInfo> schemas = new List<SchemaInfo>(); MetadataWorkspace mw = contextAdapter.ObjectContext.MetadataWorkspace; EntityType et = mw.GetItems<EntityType>(DataSpace.CSpace).FirstOrDefault(e => String.Equals(e.Name, entityType.Name)); if (null != et) { foreach (EdmProperty edmProperty in et.Properties) { SchemaInfo schema = new SchemaInfo(edmProperty.Name); schema.DataType = Type.GetType("System." + edmProperty.TypeUsage.EdmType.Name); ReadOnlyMetadataCollection<Facet> facets = edmProperty.TypeUsage.Facets; Facet facet; if (facets.TryGetValue("Nullable", true, out facet)) { schema.IsNullable = (bool)facet.Value; } if (facets.TryGetValue("MaxLength", true, out facet)) { schema.MaxLength = (int)facet.Value; } schemas.Add(schema); } foreach (EdmMember keyInfo in et.KeyMembers) { schemas.First(s => s.ColumnName == keyInfo.Name).IsKey = true; } if (et.KeyMembers.Count == 1) { SchemaInfo key = schemas.First(s => s.IsKey); if (key.DataType != CachedTypes.Guid) key.DatabaseGeneratedOption = Data.StoreGeneratedPattern.Identity; } if (schemas.Count != 0) { EntityMetaData ret = new EntityMetaData(entityType, entityType.Name); foreach (SchemaInfo schema in schemas) { ret.Add(schema, entityType.GetProperty(schema.ColumnName)); } return ret; } } return null; }
public TextFilesPersistor(IObjectContextAdapter context, IEnumerable<IEntityPersistor> entityPersistors) { _context = context as TrinetixInterviewEntities; if (_context == null) { throw new ArgumentException("DbContext has inproper type"); } // _context.Database.Log = Console.Write; _context.Configuration.AutoDetectChangesEnabled = false; _entityPersistors = entityPersistors; }
public FilePathesEntityPersistor(IObjectContextAdapter context) { _context = context; }
public LocationPersistor(IObjectContextAdapter context) { _context = context; }
/// <summary> /// Executes the entity SQL. /// </summary> private static EntityCommand GetEntityCommand(IObjectContextAdapter ctx, string esql) { var objCtx = ctx.ObjectContext; var conn = objCtx.Connection; conn.Open(); var cmd = (EntityCommand) conn.CreateCommand(); cmd.CommandText = esql; return cmd; }
public Customer() { Context = new EFDbContext(); }
public WordsEntityPersistor(IObjectContextAdapter context) { _context = context; }