EF4 CTP5:通过 MEF 模块扩展模型 - TPH - OnModelCreating
很抱歉没有找到更好的标题。我正在尝试通过 MEF 模块扩展 EF4 CTP5 模型:想法是指定一些基本实体。这些基本实体位于我的解决方案模型程序集中的 Context 类旁边。
例如,会有一个名为“变量”的实体。变量是一个非常通用的实体,我希望应用程序的某些模块指定提供更详细属性的特殊变量实体,但它们应该存储在同一个表中(TPH - 每个层次结构表)。
为此,我指定了一个接口 IModelContextExtension
public interface IModelContextExtension
{
void OnModelCreating(IModelBuilderFacade modelBuilder);
}
每个想要使用自定义变量的模块都必须导出一个实现该接口的类。在模型的 OnModelCreating 方法中,我循环每个注册的模块,并调用该模块的 OnModelCreating 方法。然后,它可以在提供的 IModelBuilderFacade 上调用“RegisterVariableType”,以声明变量派生类型(例如 MySpecialVariable2)。
** 有趣的部分:** RegisterVariableType 方法似乎工作得很好,除非 Variable-Derived-Type 位于另一个(MEF 加载的)程序集中。如果我从另一个模块注册变量,则完整的映射似乎会被损坏。因为,当我现在尝试将变量添加到其存储库时,它会在添加过程中崩溃并显示:“序列不包含元素”。如果我从加载的模块中删除类型,它会按预期工作。
如果有人感兴趣,我将发布 IRepository 的内容,但我确信,这不是问题。
这里是我的上下文(派生自 DbContext)类中的 OnModelCreating 方法:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var modelBuilderFacade = new ModelBuilderFacade(modelBuilder);
modelBuilder.Entity<Variable>().HasKey(x => new { x.Id });
////////////////////////////////////
// register derived VariableTypes
modelBuilderFacade.RegisterVariableType(typeof(MySpecialCyclicVariable));
modelBuilderFacade.RegisterVariableType(typeof(MyVerySpecialVariable));
//modelBuilder.Entity<Variable>().HasKey(x => new { x.Id }); modelBuilder.Entity<Variable>()
// .Map<MySpecialVariabe>(m => m.Requires(DiscriminatorColumn).HasValue(typeof(MySpecialVariabe).Name))
// .Map<MyVerySpecialVariable>(m => m.Requires(DiscriminatorColumn).HasValue(typeof(MyVerySpecialVariable).Name))
// .ToTable(VariableTable);
if (ModelExtensions != null)
{
foreach (var modelContextExtension in ModelExtensions)
{
modelContextExtension.OnModelCreating(modelBuilderFacade);
}
}
Map<Variable>(modelBuilder, modelBuilderFacade.VariableTypes, VariableTable);
////////////////////////////////////
}
RegisterVariableType 函数将(变量派生)类型添加到 IEnumerable存储在 modelBuilderFacade 中。
添加类型后,我调用自己的 Map 函数来进行 TPH 映射。
[Export(typeof(IModelContextExtension))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class Context : IModelContextExtension
{
public void OnModelCreating(IModelBuilderFacade modelBuilder)
{
modelBuilder.RegisterVariableType(typeof(MyVerySpecialVariable2));
}
}
这里是Map函数:
private static void Map<T>(ModelBuilder modelBuilder, IEnumerable<Type> types, string table) where T : class
{
var entityTypeConfigurarion = modelBuilder.Entity<T>();
foreach (var variableType in types)
{
if (!typeof(T).IsAssignableFrom(variableType))
{
throw new InvalidOperationException(string.Format("Cannot map type '{0}' to type {1}", variableType, typeof(T)));
}
// #1: Get the generic Map method of the EntityTypeConfiguration<T>
MethodInfo genericMapMethod = GetGenericEntityTypeConfigurationMapMethod<T>(variableType);
// #2: Get generic type of RequiredMappingActionFactory
var requiredMappingFactoryType = typeof(RequiredMappingActionFactory<>).MakeGenericType(variableType);
// #3 get the action from generic mapping factory
var action = requiredMappingFactoryType.GetProperty("RequiredMappingAction").GetValue(null, null);
entityTypeConfigurarion =
genericMapMethod.Invoke(
entityTypeConfigurarion,
BindingFlags.Public | BindingFlags.Instance,
null,
new [] { /* and the */ action /* goes here */ },
null) as EntityTypeConfiguration<T>;
}
if (entityTypeConfigurarion == null)
{
throw new CompositionException("Something went terrible wrong!");
}
entityTypeConfigurarion.ToTable(table);
}
private static MethodInfo GetGenericEntityTypeConfigurationMapMethod<T>(Type variableType) where T : class
{
var mapMethod =
typeof(EntityTypeConfiguration<T>).GetMethods().Where(
mi => mi.Name == "Map" && mi.IsGenericMethodDefinition).FirstOrDefault();
return mapMethod.MakeGenericMethod(variableType);
}
这里是RequiredMappingActionFactory
internal static class RequiredMappingActionFactory<T> where T : class
{
public static string DiscriminatorColumn = "Discriminator";
public static Action<EntityMappingConfiguration<T>> RequiredMappingAction { get { return RequiredAction; } }
public static void RequiredAction(EntityMappingConfiguration<T> configuration)
{
configuration.Requires(DiscriminatorColumn).HasValue(typeof(T).Name);
}
}
希望有人可以帮助我, 最好的问候,
切里奥, 克里斯
i am sorry to not find a better Headline. I am trying to extend a EF4 CTP5 Model via MEF Modules: The Idea is to specifiy some basic entities. Those basic entities are located next to my Context class in my solutions Model assembly.
There will be for example an entity called Variable. Variable is a very general entity and i want some modules of the application to specify Special Variable Entities witch provide more detailed properties, but they should be stored in the same table (TPH - Table per Hierarchy).
To do so, i specified an interface IModelContextExtension
public interface IModelContextExtension
{
void OnModelCreating(IModelBuilderFacade modelBuilder);
}
Each module which wants to make usage of custom variables must export a class which implements this interface. In the OnModelCreating method of the model, i loop each registered module, and call the OnModelCreating method of that module. It then can call e.g. "RegisterVariableType" on the provided IModelBuilderFacade, to announce a Variable-Derived-Type (e.g. MySpecialVariable2).
** The interesting part: **
The RegisterVariableType method seems to work very good, except if the Variable-Derived-Type is located in another (MEF-Loaded) assembly. If i register a Variable from another module, than the complete mapping seems to be damaged. Because, when i now try to add a Variable to its Repository, it crashs during the add saying: "Sequence contains no elements". If i remove the type from the loaded module, it works like expected.
I will post the IRepository stuff, if someone is interested, but i am sure, thats not the problem..
Here the OnModelCreating method from my context (derived from DbContext) class:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var modelBuilderFacade = new ModelBuilderFacade(modelBuilder);
modelBuilder.Entity<Variable>().HasKey(x => new { x.Id });
////////////////////////////////////
// register derived VariableTypes
modelBuilderFacade.RegisterVariableType(typeof(MySpecialCyclicVariable));
modelBuilderFacade.RegisterVariableType(typeof(MyVerySpecialVariable));
//modelBuilder.Entity<Variable>().HasKey(x => new { x.Id }); modelBuilder.Entity<Variable>()
// .Map<MySpecialVariabe>(m => m.Requires(DiscriminatorColumn).HasValue(typeof(MySpecialVariabe).Name))
// .Map<MyVerySpecialVariable>(m => m.Requires(DiscriminatorColumn).HasValue(typeof(MyVerySpecialVariable).Name))
// .ToTable(VariableTable);
if (ModelExtensions != null)
{
foreach (var modelContextExtension in ModelExtensions)
{
modelContextExtension.OnModelCreating(modelBuilderFacade);
}
}
Map<Variable>(modelBuilder, modelBuilderFacade.VariableTypes, VariableTable);
////////////////////////////////////
}
The RegisterVariableType function adds the (Variable derived) types to an IEnumerable stored in the modelBuilderFacade.
After the types are added, i call my own Map function to do the TPH Mapping.
[Export(typeof(IModelContextExtension))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class Context : IModelContextExtension
{
public void OnModelCreating(IModelBuilderFacade modelBuilder)
{
modelBuilder.RegisterVariableType(typeof(MyVerySpecialVariable2));
}
}
Here the Map function:
private static void Map<T>(ModelBuilder modelBuilder, IEnumerable<Type> types, string table) where T : class
{
var entityTypeConfigurarion = modelBuilder.Entity<T>();
foreach (var variableType in types)
{
if (!typeof(T).IsAssignableFrom(variableType))
{
throw new InvalidOperationException(string.Format("Cannot map type '{0}' to type {1}", variableType, typeof(T)));
}
// #1: Get the generic Map method of the EntityTypeConfiguration<T>
MethodInfo genericMapMethod = GetGenericEntityTypeConfigurationMapMethod<T>(variableType);
// #2: Get generic type of RequiredMappingActionFactory
var requiredMappingFactoryType = typeof(RequiredMappingActionFactory<>).MakeGenericType(variableType);
// #3 get the action from generic mapping factory
var action = requiredMappingFactoryType.GetProperty("RequiredMappingAction").GetValue(null, null);
entityTypeConfigurarion =
genericMapMethod.Invoke(
entityTypeConfigurarion,
BindingFlags.Public | BindingFlags.Instance,
null,
new [] { /* and the */ action /* goes here */ },
null) as EntityTypeConfiguration<T>;
}
if (entityTypeConfigurarion == null)
{
throw new CompositionException("Something went terrible wrong!");
}
entityTypeConfigurarion.ToTable(table);
}
private static MethodInfo GetGenericEntityTypeConfigurationMapMethod<T>(Type variableType) where T : class
{
var mapMethod =
typeof(EntityTypeConfiguration<T>).GetMethods().Where(
mi => mi.Name == "Map" && mi.IsGenericMethodDefinition).FirstOrDefault();
return mapMethod.MakeGenericMethod(variableType);
}
and here the RequiredMappingActionFactory
internal static class RequiredMappingActionFactory<T> where T : class
{
public static string DiscriminatorColumn = "Discriminator";
public static Action<EntityMappingConfiguration<T>> RequiredMappingAction { get { return RequiredAction; } }
public static void RequiredAction(EntityMappingConfiguration<T> configuration)
{
configuration.Requires(DiscriminatorColumn).HasValue(typeof(T).Name);
}
}
hopefully someone can help me,
best regards,
cherio,
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实体框架 4.1 RC 发布!
我尝试了一下,成功了:-)
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx
看到这里,自定义的映射功能,允许动态添加TPH映射。
以及用法示例:
干杯,
克里斯
Entity Framework 4.1 RC is released!
I tried it and i succeeded :-)
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx
See here, the custom Mapping function, which allowes to dynamically add TPH Mappings.
and the usage example:
cheers,
Chris