"Better" approach to ignoring classes when using code first and the entity framework
I am currently doing the following to remove any EF classes I don't want included. But this means I have to list all the classes.
protected override void OnModelCreating(DbModelBuilder AModelBuilder)
{
// Remove any classes that we don't want in the database. These are our derived classes
AModelBuilder.Ignore<TCompetitio开发者_开发知识库n>();
AModelBuilder.Ignore<TCompeitionLadder>();
AModelBuilder.Ignore<TCompeitionPersonRole>();
AModelBuilder.Ignore<TCountry>();
AModelBuilder.Ignore<TSport>();
AModelBuilder.Ignore<TVenue>();
}
So instead I thought I would use reflection to get the list of types in the assembly and then remove any class references that I don't want included. However I cannot seem to get this to work as the Type object is not the expected class reference type needed by Ignore(). Can anyone point me in the right direction please?
protected override void OnModelCreating(DbModelBuilder AModelBuilder)
{
// Remove any classes that we don't want in the database. These are our derived classes
Assembly objAssembly = Assembly.GetExecutingAssembly();
foreach (Type objType in objAssembly.GetTypes())
{
if (objType.BaseType.FullName.StartsWith("TEntityFramework", true, null))
{
AModelBuilder.Ignore<objType>();
}
}
}
Use reflection to call the generic function,
Instead of writing this:
AModelBuilder.Ignore<objType>();
Write this:
MethodInfo method = typeof(DbModelBuilder).GetMethod("Ignore");
MethodInfo generic = method.MakeGenericMethod(objType);
generic.Invoke(AModelBuilder, null);
精彩评论