【问题标题】:How to make a Type variable work with Linq to SQL?如何使类型变量与 Linq to SQL 一起使用?
【发布时间】:2012-08-14 12:03:00
【问题描述】:

我正在尝试制作某种通用函数,在我的代码的某个地方我有这些行

myDataContext dc = new myDataContext();
.
.
.(some code later)
.
Sucursal sucursal = dc.Sucursal.SingleOrDefault(s => s.Id == id);

效果很好。现在,当我尝试制作“通用”表单时,问题就来了

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());
}

执行此行时

FindWithId<Sucursal>(dc.Sucursal,01);

我收到以下错误

方法 'System.Reflection.MemberInfo[] GetMember(System.String)' 不允许转换 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

【问题讨论】:

    标签: c# linq-to-sql


    【解决方案1】:

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

    where DataBaseTable : class
    

    变成这样的人

    where DataBaseTable : IEntity
    

    其中 IEntity 是一个带有 Id 属性的接口,您的所有实体都可以实现它。

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

    【讨论】:

    【解决方案2】:

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

    旁注:s.GetType().GetMember("Id") 返回一个 MemberInfo 类型的值,而 MemberInfo.ToString() 不是您要查找的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多