【问题标题】:Entity Framework TPH detect discriminator columnEntity Framework TPH 检测鉴别器列
【发布时间】:2023-03-21 10:55:01
【问题描述】:

我正在尝试实现一个自定义实体框架迁移脚手架和 sql 生成器,它将自动为鉴别器列添加一个索引。为了实现这个解决方案,我想检测哪一列是鉴别器,但到目前为止我还没有找到任何官方或非官方的方法来做到这一点。

我开始检查 ColumnModel 对象的内容,这些对象作为参数传递给 SqlServerMigrationSqlGeneratorCSharpMigrationCodeGenerator 类的 Generate() 方法,但我找不到任何指向此的内容.

是否有任何方法可以从生成器内部检测鉴别器?或者可能来自上下文中包含的元数据?

【问题讨论】:

    标签: entity-framework entity-framework-6


    【解决方案1】:

    在查看了 Github 上的源代码并比一个理智的人更深入地研究 EF 之后,我想我已经想出了一个可行的解决方案。在这里发布以防其他人可能需要它:

     var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
     var entityTypes = metadata.GetItems<EntityType>(DataSpace.SSpace);
     // These are the entity sets
     var entitySets = metadata.GetItems<EntityContainer>(DataSpace.CSpace).Single().EntitySets;
     foreach (var entitySet in entitySets)
     {
       // The mapping for the entity set
       var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace).Single().EntitySetMappings.Single(s => s.EntitySet == entitySet);
       // If there is more than one mapping for the entity set...
       if (mapping.EntityTypeMappings.Count > 0)
       {
         // This shows that these mappings belong to a hierarchy
         var hierarchyMapping = mapping.EntityTypeMappings.SingleOrDefault(etm => etm.IsHierarchyMapping);
         if (hierarchyMapping == null)
           continue;
         // Get the conditions that contain the discriminator columns and values
         var conditions = mapping.EntityTypeMappings.SelectMany(etm => etm.Fragments.Single().Conditions).OfType<ValueConditionMapping>().ToList();
         if (conditions.Select(cc => cc.Column).Distinct().Count() > 1)
         {
           Debug.WriteLine($"{mapping.EntitySet.Name} has multiple mappings one of them being a hierachy mapping, but the fragments' conditions refer more than one distinct edm property");
           continue;
         }
         if (conditions.Select(cc => cc.Column).Distinct().Count() < 1)
         {
           Debug.WriteLine($"{mapping.EntitySet.Name} has a hierachy mapping, but none of the fragments' conditions are ValueConditionMappings");
           continue;
         }
         // This is the discriminator's name in the database
         var discriminatorColumn = conditions.First().Column.Name;
       }
     }
    

    我已经使用默认鉴别器列和自定义鉴别器列测试了这个解决方案,在这两种情况下它都工作正常。还使用 TPT 和 TPC 以及实体拆分和表拆分进行了测试,在所有情况下它都没有显示出任何鉴别器,所以它似乎工作正常。

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      相关资源
      最近更新 更多