本文整理汇总了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));
}
示例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);
}
}
}
示例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);
}
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}
示例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);
}
}
示例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);
}
示例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);
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}