当前位置: 首页>>代码示例>>C#>>正文


C# DbContext.GetType方法代码示例

本文整理汇总了C#中DbContext.GetType方法的典型用法代码示例。如果您正苦于以下问题:C# DbContext.GetType方法的具体用法?C# DbContext.GetType怎么用?C# DbContext.GetType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DbContext的用法示例。


在下文中一共展示了DbContext.GetType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetModel

        public virtual IModel GetModel(DbContext context, IModelBuilderFactory modelBuilderFactory)
        {
            Check.NotNull(context, "context");
            Check.NotNull(modelBuilderFactory, "modelBuilderFactory");

            return _models.GetOrAdd(context.GetType(), k => CreateModel(context, modelBuilderFactory));
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:7,代码来源:DefaultModelSource.cs

示例2: ApplyUniqueConstraints

        public void ApplyUniqueConstraints(DbContext context)
        {
            var modelTypes =
                from dbContextProperties in context.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                let propertyTypeGenericArguments = dbContextProperties.PropertyType.GetGenericArguments()
                where propertyTypeGenericArguments.Count() == 1
                select propertyTypeGenericArguments.Single();

            var modelsWithUniqueProperties =
                from modelType in modelTypes
                from property in modelType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                from uniqueAttribute in property.GetCustomAttributes(true).OfType<UniqueAttribute>()
                let propertyName = property.Name

                group propertyName by modelType into uniquePropertiesByModel

                select new {
                        Model = uniquePropertiesByModel.Key,
                        Properties = (IEnumerable<string>) uniquePropertiesByModel
                    };

            foreach (var model in modelsWithUniqueProperties)
            {
                foreach (var property in model.Properties)
                {
                    string tableName = GetTableName(model.Model);
                    string query = string.Format(UniqueConstraintQuery, tableName, property);
                    context.Database.ExecuteSqlCommand(query);
                }
            }
        }
开发者ID:guanxiaochao,项目名称:CodeExamples,代码行数:31,代码来源:UniqueAttribute.cs

示例3: ExecutePostScripts

        public static void ExecutePostScripts(DbContext context)
        {
            //Custom configurations
            var confFiles = context.GetType().Assembly
                                .GetTypes()
                                .Where(x =>
                                    string.Equals(x.Namespace,
                                        context.GetType().Namespace,
                                        StringComparison.Ordinal) && !x.IsAbstract);

            foreach (var conf in confFiles.Where(x => x.GetInterfaces().Contains(typeof(IConventionBasedConfiguration))))
            {
                var type = context.GetType().Assembly.GetType(conf.FullName);
                IConventionBasedConfiguration inst = (IConventionBasedConfiguration)Activator.CreateInstance(type);
                inst.PostScripts(context);
            }
        }
开发者ID:rkrdovrgs,项目名称:commonrepository,代码行数:17,代码来源:ConventionBasedDbContext.cs

示例4: GetTableName

 private static string GetTableName(DbContext DB, Type entityType)
 {
     Type tableType = typeof(System.Data.Entity.DbSet<>).MakeGenericType(entityType);
     var propertyInfo = DB.GetType().GetProperties().Where(p => p.PropertyType.IsGenericType && p.PropertyType == tableType).FirstOrDefault();
     if (propertyInfo == null)
         return string.Empty;
     return propertyInfo.Name;
 }
开发者ID:cbsistem,项目名称:JRIAppTS,代码行数:8,代码来源:DataServiceMethodsHelper.cs

示例5: Migrate

        /// <summary>
        /// Migrates a database using the specified context.
        /// </summary>
        public MigrationResult Migrate(DbContext context)
        {
            var commandSchedulerDbContext = context as CommandSchedulerDbContext;

            if (commandSchedulerDbContext == null)
            {
                throw new ArgumentException($"DbContext should be of type {typeof (CommandSchedulerDbContext)} but was of type {context.GetType()}");
            }

            return Migrate(commandSchedulerDbContext);
        }
开发者ID:KimberlyPhan,项目名称:Its.Cqrs,代码行数:14,代码来源:CommandSchedulerCleanupMigration.cs

示例6: GetDbMapping

        public static DbMapping GetDbMapping(DbContext context)
        {
            var contextType = context.GetType();
              if (_mappings.ContainsKey(contextType))
              {
            return _mappings[contextType];
              }

              var mapping = new DbMapping(context);
              _mappings[contextType] = mapping;
              return mapping;
        }
开发者ID:arthuryii,项目名称:WhenEntityFrameworkMeetUnity,代码行数:12,代码来源:DbMapper.cs

示例7: Create

        public IDbModelCacheKey Create(DbContext context)
        {
            string defaultSchema = null;

            var historyContext = context as HistoryContext;

            if (historyContext != null)
            {
                defaultSchema = historyContext.DefaultSchema;
            }

            return new DefaultModelCacheKey(context.GetType(), context.InternalContext.ProviderName, defaultSchema);
        }
开发者ID:jimmy00784,项目名称:entityframework,代码行数:13,代码来源:DefaultModelCacheKeyFactory.cs

示例8: PrepareForUse

 private static void PrepareForUse(DbContext instance)
 {
     if (instance.Database.Exists())
     {
         instance.Database.Initialize(false);
     }
     else
     {
         string connectionString = instance.Database.Connection.ConnectionString;
         Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Initializing database for {0} at connection string '{1}'", instance.GetType().Name, connectionString), "Information");
         instance.Database.Initialize(true);
     }
 }
开发者ID:modulexcite,项目名称:StudentSuccessDashboard,代码行数:13,代码来源:DataContextConfigurator.cs

示例9: DbContextStoredProcedurePropertyInitialiser

        public DbContextStoredProcedurePropertyInitialiser(
            DbContext context, PropertyInfo storedProcedurePropertyInfo)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (storedProcedurePropertyInfo == null) throw new ArgumentNullException("storedProcedurePropertyInfo");

            _context = context;
            _contextType = _context.GetType();
            _propertyName = storedProcedurePropertyInfo.Name;
            _propertyType = storedProcedurePropertyInfo.PropertyType;

            BuildConstructorInfo();
            EnsureConstructor();
            BuildProcedure();
            EnsureProcedure();
        }
开发者ID:dibley1973,项目名称:StoredProcedureFramework,代码行数:16,代码来源:DbContextStoredProcedurePropertyInitialiser.cs

示例10: WriteEdmx

        /// <summary>
        /// Uses Code First with the given context and writes the resulting Entity Data Model to the given
        /// writer in EDMX form.  This method can only be used with context instances that use Code First
        /// and create the model internally.  The method cannot be used for contexts created using Database
        /// First or Model First, for contexts created using a pre-existing <see cref="ObjectContext" />, or
        /// for contexts created using a pre-existing <see cref="DbCompiledModel" />.
        /// </summary>
        /// <param name="context"> The context. </param>
        /// <param name="writer"> The writer. </param>
        public static void WriteEdmx(DbContext context, XmlWriter writer)
        {
            Check.NotNull(context, "context");
            Check.NotNull(writer, "writer");

            var internalContext = context.InternalContext;
            if (internalContext is EagerInternalContext)
            {
                throw Error.EdmxWriter_EdmxFromObjectContextNotSupported();
            }

            var modelBeingInitialized = internalContext.ModelBeingInitialized;
            if (modelBeingInitialized != null)
            {
                WriteEdmx(modelBeingInitialized, writer);
                return;
            }

            var compiledModel = internalContext.CodeFirstModel;
            if (compiledModel == null)
            {
                throw Error.EdmxWriter_EdmxFromModelFirstNotSupported();
            }

            var modelStore = DbConfiguration.DependencyResolver.GetService<DbModelStore>();
            if (modelStore != null)
            {
                var storedModel = modelStore.TryGetEdmx(context.GetType());
                if (storedModel != null)
                {
                    storedModel.WriteTo(writer);
                    return;
                }
            }
            
            var builder = compiledModel.CachedModelBuilder.Clone();

            WriteEdmx(
                internalContext.ModelProviderInfo == null
                    ? builder.Build(internalContext.Connection)
                    : builder.Build(internalContext.ModelProviderInfo),
                writer);
        }
开发者ID:aspnet,项目名称:EntityFramework6,代码行数:52,代码来源:EdmxWriter.cs

示例11: Create

        public IDbModelCacheKey Create(DbContext context)
        {
            Check.NotNull(context, "context");

            string customKey = null;

            var modelCacheKeyProvider = context as IDbModelCacheKeyProvider;

            if (modelCacheKeyProvider != null)
            {
                customKey = modelCacheKeyProvider.CacheKey;
            }

            return new DefaultModelCacheKey(
                context.GetType(),
                context.InternalContext.ProviderName,
                context.InternalContext.ProviderFactory.GetType(),
                customKey);
        }
开发者ID:Cireson,项目名称:EntityFramework6,代码行数:19,代码来源:DefaultModelCacheKeyFactory.cs

示例12: AddOrGetGenericFilterContext

        /// <summary>Adds or gets the generic filter context associated with the context.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The generic filter context associated with the context.</returns>
        public static QueryFilterContext AddOrGetGenericFilterContext(DbContext context)
        {
            var key = context.GetType().FullName;
            QueryFilterContext filterContext;

            if (!CacheGenericFilterContext.TryGetValue(key, out filterContext))
            {
                lock (GenericFilterContextLock)
                {
                    if (!CacheGenericFilterContext.TryGetValue(key, out filterContext))
                    {
                        filterContext = new QueryFilterContext(context, true);
                        CacheGenericFilterContext.Add(key, filterContext);
                    }
                }
            }

            return filterContext;
        }
开发者ID:DebugOfTheRoad,项目名称:EntityFramework-Plus,代码行数:22,代码来源:QueryFilterManager.cs

示例13: EntityFrameworkHook

        public EntityFrameworkHook(DbContext context, SaveChangesHookHandler funcDelegate)
        {
            _context = context;
            _funcDelegate = funcDelegate;
            SaveChanges += _funcDelegate;
            var internalContext = _context.GetType()
                                           .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
                                           .Where(p => p.Name == "InternalContext")
                                           .Select(p => p.GetValue(_context, null))
                                           .SingleOrDefault();

            var objectContext = internalContext.GetType()
                                           .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                           .Where(p => p.Name == "ObjectContext")
                                           .Select(p => p.GetValue(internalContext, null))
                                           .SingleOrDefault();

            var saveChangesEvent = objectContext.GetType()
                                                .GetEvents(BindingFlags.Public | BindingFlags.Instance)
                                                .SingleOrDefault(e => e.Name == "SavingChanges");
            var handler = Delegate.CreateDelegate(saveChangesEvent.EventHandlerType, this, "OnSaveChanges");
            saveChangesEvent.AddEventHandler(objectContext, handler);
        }
开发者ID:ash53,项目名称:SQLCM,代码行数:23,代码来源:EntityFrameworkHook.cs

示例14: DbContextInfo

        /// <summary>
        ///     Called internally when a context info is needed for an existing context, which may not be constructable.
        /// </summary>
        /// <param name="context"> The context instance to get info from. </param>
        internal DbContextInfo(DbContext context)
        {
            Check.NotNull(context, "context");

            _contextType = context.GetType();
            _appConfig = AppConfig.DefaultInstance;

            var internalContext = context.InternalContext;
            _connectionProviderName = internalContext.ProviderName;

            _connectionInfo = new DbConnectionInfo(internalContext.OriginalConnectionString, _connectionProviderName);

            _connectionString = internalContext.OriginalConnectionString;
            _connectionStringName = internalContext.ConnectionStringName;
            _connectionStringOrigin = internalContext.ConnectionStringOrigin;
        }
开发者ID:jwanagel,项目名称:jjwtest,代码行数:20,代码来源:DbContextInfo.cs

示例15: GetCustomMetaData

        public string GetCustomMetaData(DbContext dbContext)
        {
            var customMetaData = new CustomMetaData();
            Type type = dbContext.GetType();

            // Get all DbSets from DbContext.
            List<PropertyInfo> propertyInfos = type.GetProperties().Where(p => p.PropertyType.Name.Equals("DbSet`1")).ToList();

            // Proces DbSets.
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                var structuralType = new StructuralType();

                // Proces Entity.
                Type entityType = propertyInfo.PropertyType.GenericTypeArguments[0];
                [email protected] = entityType.Namespace;
                structuralType.shortName = entityType.Name;

                // Get all entity validation attributes (Attribute must implement IEntityValidator).
                IEnumerable<Attribute> entityAttributes = entityType.GetCustomAttributes().Where(x => x is IEntityValidator);

                // Proces entity validation attributes.
                foreach (Attribute entityAttribute in entityAttributes)
                {
                    // Add entity validation attributes to custom metadata.
                    var metaData = new CustomEntityMetaData();
                    structuralType.custom.validators.Add(entityAttribute as IEntityValidator);
                }

                // Get all fields (SQL Server columns) per Entity (SQL Server Table).
                PropertyInfo[] epis = entityType.GetProperties();

                // Proces entity properties.
                foreach (PropertyInfo epi in epis)
                {
                    var dataProperty = new DataProperty
                    {
                        nameOnServer = epi.Name
                    };

                    if (epi.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase))
                    {
                        dataProperty.isPartOfKey = true;
                    }

                    // Get all field validation attributes.
                    IEnumerable<Attribute> epiAttributes = epi.GetCustomAttributes();

                    // Proces field validation attributes.
                    foreach (Attribute epiAttribute in epiAttributes)
                    {
                        dataProperty.custom.validators.Add(epiAttribute);
                    }

                    structuralType.dataProperties.Add(dataProperty);
                }

                customMetaData.structuralTypes.Add(structuralType);
            }

            return JsonConvert.SerializeObject(customMetaData);
        }
开发者ID:husni1992,项目名称:Research,代码行数:62,代码来源:CustomMetaDataBuilder.cs


注:本文中的DbContext.GetType方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。