2016-12-10 14 views
1

クラスオブジェクト型からDbSet名を取得しようとしています。これは、DbContextでDbSetの定義です:今クラスオブジェクト型からDbSet名を取得

public DbSet<User.Role> Roles { get; set; } 

typeof(Role)から私はDbSet「役割」の名前を取得する必要があります。

これを取得する方法はありますか?

+0

私はいくつかの質問を持っている:あなたはEntity Frameworkの6を使用している?あなたはDbContextで 'Property'が呼び出さ' Roles'または 'DbSet 'だけの種類を見つける必要がありますか? –

+0

こんにちはアンドレ。はい!私はEF6を使用しています。文字列に "Roles"という名前を付けるだけでOKです。 typeof(役割)から –

答えて

2

これはあなたの後ですか?

public static void Main() 
{ 
    var roleType = typeof(User.Role); 

    var context = new FakeDbContext(); 

    var propertyInfo = GetDbSetProperty(roleType, context); 

    Console.WriteLine(propertyInfo.Name); 
} 

public static PropertyInfo GetDbSetProperty(Type typeOfEntity, FakeDbContext context) 
{ 
    var genericDbSetType = typeof(DbSet<>); 
    // typeof(DbSet<User.Role>); 
    var entityDbSetType = genericDbSetType.MakeGenericType(typeOfEntity); 

    // DbContext type 
    var contextType = context.GetType(); 

    return contextType 
     .GetProperties(BindingFlags.Public | BindingFlags.Instance) 
     .Where(p => p.PropertyType == entityDbSetType) 
     .FirstOrDefault();  
} 

public class FakeDbContext 
{ 
    public DbSet<User.Role> Roles { get; set; } 
} 

public class DbSet<T> 
{ 
} 

public class User 
{ 
    public class Role 
    { 
    } 
} 
関連する問題