我想要获得的是来自实体的属性并对值求和。我正在使用泛型,实体的类型和属性的名称在运行时是已知的。以下(简化)代码编译良好,但抛出“对象与目标类型不匹配”。尝试从实体获取属性时。这是代码:
public class SomeModel
{
public int ValueA { get; set; }
public int ValueB { get; set; }
}
public class SomeViewModel
{
public int ViewValue { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
IEnumerable<SomeModel> data = GetData();
var result = SumValues(data, a => new SomeViewModel { ViewValue = a.ValueA });
return Content(string.Format("Total is: {0}", result));
}
private int SumValues<T, TRes>(IEnumerable<T> data, Func<T, TRes> transformation)
{
var transformedData = data.Select(transformation);
Type type = typeof(TRes);
PropertyInfo property = type.GetProperty("ViewValue");
IEnumerable<int> listOfValues = property.GetValue(transformedData, null) as IEnumerable<int>;
var sum = listOfValues.Sum();
return sum;
}
private IEnumerable<SomeModel> GetData()
{
var data = new List<SomeModel>();
Random random;
for (int i = 0; i < 1000; i++)
{
random = new Random(i);
data.Add(new SomeModel { ValueA = random.Next(5,100), ValueB = random.Next(20,80) });
}
return data;
}
}
我在这里生成假数据,但真正的应用程序是使用 EF 从数据库中获取数据。泛型对我来说是新的,所以请任何指出我正确方向的建议将不胜感激。