EF4 CTP5:通过 MEF 模块扩展模型 - TPH - OnModelCreating

发布于 2024-10-18 07:51:32 字数 4924 浏览 1 评论 0原文

很抱歉没有找到更好的标题。我正在尝试通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灵芸 2024-10-25 07:51:32

实体框架 4.1 RC 发布!
我尝试了一下,成功了:-)

http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx

看到这里,自定义的映射功能,允许动态添加TPH映射。

protected void MapEntity(
    DbModelBuilder modelBuilder, Type entityType, string toTable, string discriminatorColumn = "Discriminator")
{
    var method =
        GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(
            mi => mi.Name.StartsWith("MapEntity") && mi.IsGenericMethodDefinition).FirstOrDefault();

    var genericMethod = method.MakeGenericMethod(entityType);

    genericMethod.Invoke(this, new object[] { modelBuilder, toTable, discriminatorColumn });
}

protected void MapEntity<T>(
    DbModelBuilder modelBuilder, string toTable, string discriminatorColumn = "Discriminator")
    where T : class, IEntity
{
    var config = modelBuilder.Entity<T>().Map(
        entity =>
            {
                entity.MapInheritedProperties();
                entity.Requires(discriminatorColumn).HasValue(typeof(T).FullName).IsOptional();
            });

    config.ToTable(toTable);
}

以及用法示例:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    MapEntity<Variable>(modelBuilder, toTable: "Variables");
    MapEntity<Variable2>(modelBuilder, toTable: "Variables");

    foreach (var entityType in ModelExtensions.SelectMany(modelExtension => modelExtension.IntroduceModelEntities()))
    {
        MapEntity(modelBuilder, entityType, toTable: "Variables");
    }
}

干杯,
克里斯

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.

protected void MapEntity(
    DbModelBuilder modelBuilder, Type entityType, string toTable, string discriminatorColumn = "Discriminator")
{
    var method =
        GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(
            mi => mi.Name.StartsWith("MapEntity") && mi.IsGenericMethodDefinition).FirstOrDefault();

    var genericMethod = method.MakeGenericMethod(entityType);

    genericMethod.Invoke(this, new object[] { modelBuilder, toTable, discriminatorColumn });
}

protected void MapEntity<T>(
    DbModelBuilder modelBuilder, string toTable, string discriminatorColumn = "Discriminator")
    where T : class, IEntity
{
    var config = modelBuilder.Entity<T>().Map(
        entity =>
            {
                entity.MapInheritedProperties();
                entity.Requires(discriminatorColumn).HasValue(typeof(T).FullName).IsOptional();
            });

    config.ToTable(toTable);
}

and the usage example:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    MapEntity<Variable>(modelBuilder, toTable: "Variables");
    MapEntity<Variable2>(modelBuilder, toTable: "Variables");

    foreach (var entityType in ModelExtensions.SelectMany(modelExtension => modelExtension.IntroduceModelEntities()))
    {
        MapEntity(modelBuilder, entityType, toTable: "Variables");
    }
}

cheers,
Chris

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文