Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使类型变量与Linq to SQL一起工作?_C#_Linq To Sql - Fatal编程技术网

C# 如何使类型变量与Linq to SQL一起工作?

C# 如何使类型变量与Linq to SQL一起工作?,c#,linq-to-sql,C#,Linq To Sql,我正在尝试创建一个类属函数,在代码的某些地方,我有以下几行代码 myDataContext dc = new myDataContext(); . . .(some code later) . Sucursal sucursal = dc.Sucursal.SingleOrDefault(s => s.Id == id); 它工作得很好。现在,当我尝试创建“通用”表单时,问题来了 公共静态void FindWithId(表,int-id) where DataBaseTable:clas

我正在尝试创建一个类属函数,在代码的某些地方,我有以下几行代码

myDataContext dc = new myDataContext();
.
.
.(some code later)
.
Sucursal sucursal = dc.Sucursal.SingleOrDefault(s => s.Id == id);
它工作得很好。现在,当我尝试创建“通用”表单时,问题来了

公共静态void FindWithId(表,int-id)
where DataBaseTable:class
{                    
DataBaseTable t=table.SingleOrDefault(s=>s.GetType().GetMember(“Id”).ToString()==Id.ToString());
}
执行此行时

FindWithId<Sucursal>(dc.Sucursal,01);
FindWithId(dc.Sucursal,01);
我得到以下错误

El método'System.Reflection.MemberInfo[]GetMember(System.String)'不接受SQL的转换

大致可以翻译为:

方法“System.Reflection.MemberInfo[]GetMember(System.String)”不支持转换为SQL

我能做些什么来让它工作

谢谢

更新解决方案

我一直在努力寻找解决方案,直到我发现这一点,它给出了一个非常彻底的答案,但为了我的目的,我对它进行了调整:

  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();
    }
}
公共类DBAccess
{
公共虚拟数据库表GetById(int-id,Table-Table),其中DataBaseTable:class
{
var itemParameter=Expression.Parameter(typeof(DataBaseTable),“item”);
var whereExpression=Expression.Lambda
(
表达式。相等(
表达式.属性(
itemParameter,
“Id”
),
表达式.常量(id)
),
新[]{itemParameter}
);
返回表.Where(whereExpression.Single();
}
}

希望它对某些人有用:p

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

where DataBaseTable : class

where DataBaseTable : IEntity
其中,IEntity是一个接口,其上有一个Id属性,您的所有实体都可以实现该属性


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

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


旁注:
s.GetType().GetMember(“Id”)
返回类型为
MemberInfo
的值,并且
MemberInfo.ToString()
不是您要找的。您的回答让我想到了这个线程,所以我认为它和anser:p>一样好
where DataBaseTable : IEntity