2016-04-01 18 views
1

クラスのスキーマ名を直接または間接的に実装するインターフェイスに基づいて設定するEF規則を作成しました。EFエンティティセットからオブジェクトの型を取得する方法

public class TableNameConvention<T> : IStoreModelConvention<EntitySet> 
{ 
    private readonly string SchemaName; 

    public TableNameConvention(string schemaName) 
    { 
     this.SchemaName = schemaName; 
    } 

    public virtual void Apply(EntitySet entitySet, DbModel model) 
    { 
     // Get the name of the Entity 
     string name = entitySet.Name; 

     // Check TEntityType Assembly for entitySet type 
     Type type = typeof(T).Assembly.GetTypes().Where(x => x.Name == name).SingleOrDefault(); 

     // Check if type was found 
     if (type != null) 
     { 
      // Check if type implements Type Parameter and if so, set schema 
      if (typeof(T).IsAssignableFrom(type)) entitySet.Schema = SchemaName; 
     } 

     entitySet.Table = FormatName(name); 
    } 

これは95%の時間で正常に動作します。ただし、アセンブリ内に同じ名前の別のクラスがある場合は、デフォルトを返します。 FirstOrDefaultに変更することはできますが、実際に探しているものが最初のものであるという保証はありません。

完全修飾名がなければ100%になることはありませんが、正しいタイプを取得する可能性を高めるための提案はありますか?

UPDATE

私は次のように変更:

Type type = AppDomain.CurrentDomain.GetAssemblies() 
         .SelectMany(t => t.GetTypes()) 
         .Where(t => t.IsClass && t.Namespace == typeof(T).Namespace) 
         .FirstOrDefault(t => t.Name.Equals(name)); 

派生クラスはしかし、基底クラスと同じ名前空間にある場合にのみ動作します。だから誰か他の提案があれば、助けてください!

答えて

0

短い答えは、EF EntitySetから、少なくともではないストレージモデルで直接、企業の実際のTypeを取得する方法がないということです。 LINQクエリの方法はないのAppDomain

Type type = AppDomain.CurrentDomain.GetAssemblies() 
        .SelectMany(t => t.GetTypes()) 
        .Where(t => t.IsClass && t.Namespace == this.Namespace) 
        .FirstOrDefault(t => t.Name.Equals(name)); 
0

これは機能しますか?

 // Check TEntityType Assembly for entitySet type 
     Type type = typeof(T).Assembly.GetTypes().Where(x => x == entitySet.GetType()).SingleOrDefault(); 
+0

から型を取得する場所を更新し、その後

private readonly string SchemaName; private readonly string Namespace; public TableNameConvention(string schemaName, string @namespace) { this.SchemaName = schemaName; this.Namespace = @namespace; } 

をして:

仕事上のコードを作るためには、私は次のようにクラスを更新します作業。 'entitySet'変数は、それが表す基本クラスの実際の型ではなく、' EntitySet'型のオブジェクトを参照します。 –

関連する問題