如何使Type变量与Linq to SQL一起使用? [英] How to make a Type variable work with Linq to SQL?

查看:53
本文介绍了如何使Type变量与Linq to SQL一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个通用的函数,在我的代码的某些地方我有这些行

I'm trying to make a generic function of sorts, in some place of my code I have these lines

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

效果很好.现在,当我尝试制作通用"表格

which works wonderfully. Now, the problem comes when I try to make the "generic" form

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

我遇到以下错误

El'Método'System.Reflection.MemberInfo [] GetMember(System.String)'没有SQL对话.

El método 'System.Reflection.MemberInfo[] GetMember(System.String)' no admite la conversión a SQL.

大致翻译为:

方法'System.Reflection.MemberInfo [] GetMember(System.String)'不支持到SQL的转换.

Method 'System.Reflection.MemberInfo [] GetMember (System.String)' does not support the conversion to SQL.

我可以做些什么?

谢谢!

更新解决方案

我一直在寻找解决方案,直到遇到这个

I was struggling to find a solution, until i came upon this thread, it gives a very thorough answer, but to my purpose i adapted it to this:

  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

推荐答案

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

If you only want a generic method for getting the Id property, you could change

where DataBaseTable : class

要做类似的事情

where DataBaseTable : IEntity

IEntity是一个具有Id属性的接口,您的所有实体都可以实现.

Where IEntity is an interface with an Id property on it which all of your entities could implement.

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

The reason you get the error you do is because it is trying to convert the reflection methods into SQL, which doesn't make any sense in SQL as there are no 'methods' on tables.

这篇关于如何使Type变量与Linq to SQL一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆