2012-08-14 43 views
0

我试图做各种各样的通用功能,在一些地方我的代码我有这些行如何使一个类型变量与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

回答

2

如果您只想获得Id属性的通用方法,则可以更改

where DataBaseTable : class 

要像

where DataBaseTable : IEntity 

哪里IEntity是与它包含一个ID属性所有的实体可以实现一个接口。

你得到错误的原因是因为它试图将反射方法转换为SQL,这在SQL中没有任何意义,因为表上没有'方法'。

+0

你的答案把我带到这个线程http://stackoverflow.com/questions/735140/c-sharp-linq-to-sql-refactoring-this-generic-getbyid-method,所以我觉得它是一样好anser:P – Mol 2012-08-14 23:35:19

0

你不能这样,因为你基本上试图在SQL中使用反射方法:作为参数SingleOrDefault()传递的内容将被转换为SQL。

附注:s.GetType().GetMember("Id")返回值类型MemberInfo,而MemberInfo.ToString()不是你要找的。

相关问题