我试图做各种各样的通用功能,在一些地方我的代码我有这些行如何使一个类型变量与Linq to SQL一起工作?
myDataContext dc = new myDataContext();
.
.
.(some code later)
.
Sucursal sucursal = dc.Sucursal.SingleOrDefault(s => s.Id == id);
这奇妙的作品。现在,问题是当我试图让“通用”的形式
执行这条线FindWithId<Sucursal>(dc.Sucursal,01);
时
public static void FindWithId<DataBaseTable>(Table<DataBaseTable> table, int id)
where DataBaseTable : class
{
DataBaseTable t = table.SingleOrDefault(s => s.GetType().GetMember("Id").ToString() == id.ToString());
}
我得到以下错误
萨尔瓦多方法方法“的System.Reflection .MemberInfo [] GetMember(System.String)'no admite laconversióna SQL。
其大致翻译到:
方法 'System.Reflection.MemberInfo [] GetMember(System.String)' 不支持转换到SQL。
我该怎么做才能做到这一点?
谢谢!
更新解决方案
我挣扎着找到一个解决方案,直到我来了在这个thread,它提供了一个非常完整的答案,但我的目的,我就适应了这个:
public class DBAccess
{
public virtual DataBaseTable GetById<DataBaseTable>(int id, Table<DataBaseTable> table) where DataBaseTable : class
{
var itemParameter = Expression.Parameter(typeof(DataBaseTable), "item");
var whereExpression = Expression.Lambda<Func<DataBaseTable, bool>>
(
Expression.Equal(
Expression.Property(
itemParameter,
"Id"
),
Expression.Constant(id)
),
new[] { itemParameter }
);
return table.Where(whereExpression).Single();
}
}
希望对某人有用:P
你的答案把我带到这个线程http://stackoverflow.com/questions/735140/c-sharp-linq-to-sql-refactoring-this-generic-getbyid-method,所以我觉得它是一样好anser:P – Mol 2012-08-14 23:35:19