簡體   English   中英

使用泛型進行反射

[英]Reflection using generics

我想返回使用反射保存到類中的一系列DbSet對象的屬性,但是為了以單個方法訪問此數據,我需要傳遞一個變量作為訪問器以返回的屬性。該對象。

目前,我設法返回了所有DbSet對象的屬性,但是代碼看起來很干。

public DbSet<Foo> Foo {get;set;}
public DbSet<Bar> Bar {get;set;}

public List<string> GetPropertiesFoo()
{
    DbContext client = new DbContext();
    return client.Foo.GetType().GetProperties().Select(e => e.Name).ToList();
}
public List<string> GetPropertiesBar()
{
    DbContext client = new DbContext();
    return client.Bar.GetType().GetProperties().Select(e => e.Name).ToList();
}

我的意圖是重構它,以便它接受DbSet名稱作為參數並返回單個屬性列表,而不是所有屬性列表。

您正在尋找這樣的東西來一次完成所有操作。 請注意,此代碼非常冗長,因此可以解釋每個步驟:

// Make the method generic so we can use it on any context
public List<string> GetProperties<TContext>(string dbSetName = "")
    where TContext : DbContext // Make sure we have a Dbcontext
{
    var propertyNames = typeof(TContext)

        // Get all properties of context
        .GetProperties() 

         // Filter out so we only have DbSet<> types
        .Where(pi => pi.PropertyType.IsGenericType &&
                     typeof(DbSet<>).IsAssignableFrom(pi.PropertyType.GetGenericTypeDefinition()))

        // If a DbSet name has been specified, filter it out
        .Where(pi => string.IsNullOrEmpty(dbSetName) || pi.Name == dbSetName)

        // Get the generic type e.g. Foo
        .Select(pi => pi.PropertyType.GetGenericArguments()[0])

        // Get the individual properties of the entity types
        .Select(t => t.GetProperties())

        // Get all of the property names
        .SelectMany(x => x.Select(pi => pi.Name)); 

    return propertyNames.ToList();
}

並像這樣使用它:

// All properties for all sets
var allProperties = GetProperties<MyContext>();

// Only properties for the Foo set
var fooProperties = GetProperties<MyContext>("Foo");

我想你可能會喜歡這樣的事情

public List<string> GetProperties(string model)
{
   var property = 
      this.GetType()
      .GetProperties()
      .Where(p=>p.Name == model)
      .FirstOrDefault();

   if(property == null) return IEnumerable.Empty<string>().ToList();
   return property
      .PropertyType
      .GetGenericArguments()[0]
      .GetProperties()
      .Select(p=>p.Name)
      .ToList();
}
public List<Foo> GetFooFromBar(string bar)
{
     return = typeof(FooContext)//a list of DbSets (DbSet<Foo>, DbSet<Bar>)
    .GetProperties()
    .Where(e => e.Name == bar)//Filter based on the name of DbSet entered
    .GetType()//Get Type of the object returned (the DbSet with a matching name)
    .GetGenericArguments()[0]//Get the first item in the array of PropertyInfo
    .GetProperties()//Get a list of the properties of the DbSet within the Context
    .ToList();
    return bar;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM