使用Linq而不是SQL字符串构造查询 [英] Construct Query with Linq rather than SQL strings

查看:55
本文介绍了使用Linq而不是SQL字符串构造查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2.0服务器控件,它使用动态查询的形式大致如下:

I've got a 2.0 server control that uses a dynamic query roughly in the form:

string sql = "Select " + columnvariable + " FROM " + tablenamevariable

因此,显然,您可以从数据库中的任何有效表中为其指定任何有效的列名,并且它将该列中的值返回到DataReader中(在这种情况下).

So, obviously, you could give it any valid column name from any valid table in the DB and it would return the values in the column into a DataReader (in this case).

我正在尝试减少代码库中显式的零碎SQL的数量,并且希望在LINQ中这样做.是否有捷径可寻?甚至建议吗?我想在这种情况下生成的零散SQL是如此通用,以至于在这种情况下不会真正造成安全性问题.

I'm trying to cut down on the amount of explicit piecemeal SQL in the codebase and would prefer to do this in LINQ. Is there an easy way to do this? Is it even advisable? I suppose that the resulting piecemeal SQL in this case would be so generic as to not really pose a security problem in this instance.

即使如此,它似乎还是有一些相当基本的功能,所以我很好奇.我已经在我的项目中包含了System.Linq.Dynamic,但是这似乎停止了让程序员动态选择他们想要从哪个表中获取动态列的工作.

Even so, it seems like some fairly basic functionality so I'm curious. I've got as far as including System.Linq.Dynamic in my project but this seems to stop shy of allowing a programmer to dynamically select which table they want a dynamic column from.

这并不是要讨论.我想要一个答案,例如是的,这是可能的并且是微不足道的,这就是方法..."或是,但是只有当您构造了这套精心设计的处理程序类并基本上重写了一部分LINQ时,这就是方法..."

I don't mean this to be a discussion. I'd like an answer like "Yes, this is possible and trivial, here's how..." or "Yes, but only if you construct this elaborate set of handler classes and basically rewrite parts of LINQ, here's how..."

但是,我很想知道人们是否认为在LINQ中做这种事情最好地描述为a)一个愚蠢的好主意或b)疯狂的谈话.

I would, however, be interested to know whether people think doing this kind of thing in LINQ could best be described as a) a jolly good idea or b) crazy talk.

推荐答案

由于您一直在寻找简单的答案...不,这在LINQ中是不可能的.

Since you were looking for a straightforward answer ... No, this is not possible in LINQ.

LINQ本质上是强类型的,而您正在寻找完全动态的东西.如果您的表和列是运行时变量(即字符串),那么您的SQL将需要是字符串...否则您将需要使用ORM(NHibernate,L2S,EF等)来访问数据.

LINQ is inherently strongly typed, while you're looking for something entirely dynamic. If your table and column are runtime variables (i.e. strings) then your SQL will need to be a string ... or you would need to use an ORM (NHibernate, L2S, EF, etc) to access the data.

这篇关于使用Linq而不是SQL字符串构造查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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