我试图做一个通用的函数,在我的代码的某些地方我有这些行
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 : IEntityIEntity是一个具有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一起使用?
发布评论