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

时间:2011-02-21 16:04:22

标签: c# .net entity-framework-4 mef entity-framework-ctp5

我很遗憾找不到更好的标题。我试图通过MEF模块扩展EF4 CTP5模型:想法是指定一些基本实体。这些基本实体位于我的解决方案模型程序集中的Context类旁边。

例如,将有一个名为Variable的实体。变量是一个非常通用的实体,我希望应用程序的某些模块指定特殊变量实体提供更详细的属性,但它们应存储在同一个表中(TPH - 每个层次结构的表)。

为此,我指定了一个接口IModelContextExtension

public interface IModelContextExtension
{
    void OnModelCreating(IModelBuilderFacade modelBuilder);
}

每个想要使用自定义变量的模块必须导出一个实现此接口的类。在模型的OnModelCreating方法中,我循环每个注册的模块,并调用该模块的OnModelCreating方法。然后它可以调用例如提供的IModelBuilderFacade上的“RegisterVariableType”,用于宣布Variable-Derived-Type(例如MySpecialVariable2)。

**有趣的部分:** RegisterVariableType方法似乎工作得非常好,除非Variable-Derived-Type位于另一个(MEF-Loaded)程序集中。如果我从另一个模块注册一个变量,那么完整的映射似乎就会被破坏。因为,当我现在尝试向其存储库添加变量时,它会在添加说法中崩溃:“序列不包含任何元素”。如果我从加载的模块中删除类型,它会像预期的那样工作。

我会发布IRepository的东西,如果有人有兴趣,但我相信,那不是问题..

这里是我的上下文中的OnModelCreating方法(派生自DbContext)类:

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函数将(变量派生)类型添加到存储在modelBuilderFacade中的IEnumerable。

添加类型后,我调用自己的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);
    }
}
希望有人可以帮助我, 最好的问候,

cherio, 克里斯

1 个答案:

答案 0 :(得分:0)

实体框架4.1 RC已发布! 我试过了,我成功了: - )

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

请参见此处的自定义Mapping函数,该函数允许动态添加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");
    }
}

欢呼声, 克里斯