我有ID的一个表中(作为一个参数提供表名)返回的行Web服务超过一定ID(也供给作为参数)更大。我们假设这些ID是连续的。
我使用LINQ to SQL的数据库交互,所以我想回报新行作为:
List<WhateverObject>
因为我们只知道在运行时的表名,我不能以正常方式使用Linq这使事情变得更加复杂。
问:
的代码如下(和它的作品)。我怎样才能简化它?看起来过于复杂。
private object GetUpdateList(string tableName, int Id, DataClassesDataContext db)
{
PropertyInfo pi = db.GetType().GetProperty(tableName);
var table = pi.GetValue(db, null);
// Get type of object within the table.
Type genericType = table.GetType().GetGenericArguments()[0];
// The Where method lives on the Enumerable type in System.Linq
var whereMethods = typeof(System.Linq.Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Where");
// There are actually 2 where methods - we want the one with 2 parameters
MethodInfo whereMethod = null;
foreach (var methodInfo in whereMethods)
{
var paramType = methodInfo.GetParameters()[1].ParameterType;
if (paramType.GetGenericArguments().Count() == 2)
{
// we are looking for Func<TSource, bool>, the other has 3
whereMethod = methodInfo;
break;
}
}
Func<object, bool> IdEquals = BuildEqFuncFor("Id", Id);
whereMethod = whereMethod.MakeGenericMethod(genericType);
var result = whereMethod.Invoke(table, new object[] { table, IdEquals });
MethodInfo toListMethod = typeof(System.Linq.Enumerable).GetMethod("ToList").MakeGenericMethod(genericType);
return toListMethod.Invoke(result, new object[] { result });
}
// Build lambda expression for use in Linq
private static Func<object, bool> BuildEqFuncFor(string prop, object val)
{
// We know we are comparing integers here so cast them.
// There is probably a more general solution.
return t => (int)t.GetType().InvokeMember(prop, BindingFlags.GetProperty, null, t, null) > (int)val;
}
要拿出这种解决方案我不得不引用以下问题:
- How do I invoke an extension method using reflection?
- How to call extension method "ElementAt"of List<T> with reflection?
- How to get the type of T from a member of a generic class or method?
- Convert func to predicate using reflection in C#
不要抛弃你的问题,但你是否处于无法重构的情况?对于如此简单的事情来说,这似乎有很多工作要做。它是否需要如此通用? – 2012-07-26 02:01:51
你会建议什么? – 2012-07-26 02:07:38
只要使它强制输入?传递表名和ID。从数据库中选择它并返回请求的行。返回一个'IEnumerable'并且在一天内调用它。 –
2012-07-26 02:12:49