如何使Type变量与Linq to SQL一起使用?

编程入门 行业动态 更新时间:2024-10-11 07:35:33
本文介绍了如何使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一起使用?

本文发布于:2023-11-22 00:24:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615260.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Type   SQL   Linq

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!