0

以以下模型为例。

public class FooModel
{
    public FooModel()
    {
        Bars= new List<BarModel>();
    }

    [ManyToMany]
    public IList<BarModel> Bars{ get; set; }
}
public class BarModel
{
    public int Id { get; set; }
}

我需要List<BarModel>从一个对象推断出,并从列表中的每个 BarModelfooModel构建一个。Dictionary<string, object>


假设我创建了以下对象。

var fooModel = new FooModel();
var bar1 = new BarModel {Id = 1};
var bar2 = new BarModel {Id = 2};
fooModel.Bars = new List<BarModel>{bar1,bar2};

现在我想获取 Foo 中具有该属性的所有[ManyToMany]属性。

// First I call the method and pass in the model
DoSomething(fooModel);
// Next I extract some values (used elsewhere)
public DoSomething<TModel>(IModel model){

    var dbProvider = ...;
    var mapper = new AutoMapper<TModel>();
    var tableName = GetTableName( typeof( TModel ) );

    UpdateJoins( dbProvider, fooModel, tableName, mapper );
}
// Finally I begin dealing with the collection.
private static void UpdateJoins<TModel> ( IDbProvider dbProvider, TModel model, string tableName, IAutoMapper<TModel> mapper ) where TModel : class, new()
{
    foreach (
        var collection in
             model.GetType()
                  .GetProperties()
                  .Where( property => property.GetCustomAttributes( typeof( ManyToManyAttribute ), true ).Any() ) )
    {

        if ( !IsGenericList( collection.PropertyType ) )
            throw new Exception( "The property must be a List" );

        // Stuck Here - pseudo code
        //====================
        foreach (loop the collection)

             var collectionName = ...;  // Bar
             var nestedPropertyName = ...;  // Id
             var rightKey = collectionName + nestedPropertyName; // BarId
             var nestedPropertyValue = ...; // 1

    }
}

在上面的示例中,OUTERforeach只会运行一次,因为其中只有一个 PropertyFooModel用该[ManyToMany]属性装饰。

因此PropertyInfo property是一个List<BarModel>

如何执行上述 INNERforeach并提取所需数据?

4

1 回答 1

1

这可能会让你走上正轨。这个想法是,如果您遇到 [ManyToMany] / 通用列表,您可以使用对同一方法的递归调用来反映它,然后将返回的值展平以形成唯一键。您可能需要对其进行调整以适应您的问题。下面的代码返回一个字典,其中包含从集合名称、索引和属性名称构建的格式化键字符串。例如:

Bars[0].Id = 1
Bars[1].Id = 2

代码:

//This is just a generic wrapper for the other Reflect method
private static Dictionary<string, string> Reflect<TModel>(TModel Model)
{
  return Reflect(Model.GetType(), Model);
}

private static Dictionary<string, string> Reflect(Type Type, object Object)
{
  var result = new Dictionary<string, string>();

  var properties = Type.GetProperties();

  foreach (var property in properties)
  {
    if (
      property.GetCustomAttributes(typeof(ManyToManyAttribute), true).Any() &&
      property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
    {
      var genericType = property.PropertyType.GetGenericArguments().FirstOrDefault();
      var listValue = (IEnumerable)property.GetValue(Object, null);

      int i = 0;
      foreach (var value in listValue)
      {
        var childResult = Reflect(genericType, value);
        foreach (var kvp in childResult)
        {
          var collectionName = property.Name;
          var index = i;
          var childPropertyName = kvp.Key;
          var childPropertyValue = kvp.Value;

          var flattened = string.Format("{0}[{1}].{2}", collectionName, i, childPropertyName);
          result.Add(flattened, childPropertyValue);
        }

        i++;
      }
    }
    else
    {
      result.Add(property.Name, property.GetValue(Object, null).ToString());
    }
  }

  return result;

}
于 2013-11-05T03:06:14.837 回答