开发者

How can i add a condition string to an sql query in an var type

Im working on an so开发者_StackOverflowurce code with an sql query in a VAR type like

var query = select ... from ... where ... ;

is it possible to add an dynamic "where clause" like

string condition = "where x.x > x.y"; 

e.g. var query = select ... from ... + condition;

Iam sorry for my bad english


You are not clearly stating how your query looks like. Is it a result of a LINQ operation or simply a String?

The keyword var is only usable for design time. The compiler will substitute it with the correct datatype.

If you SQL query is a string, like

var query = "Select ... from ... where ..";

then

string condition = "where x.x > x.y";
query += condition;

is valid because both variables are strings. You can't combine a non string type with a string the way your code suggests.

I do now assume that you are using a LINQ syntax. It is possible to add such conditions to a linq query per code, I think the keywords linq query builder, expression tree and predicate should get you started.

I'd strongly suggest that you stop using the var keyword without exactly knowing what it does and where to use it.


Dynamic Linq exists specifically to solve late-bound scenarios for LINQ:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Allows constructs such as:

NorthwindDataContext northwind = new NorthwindDataContext();

var query = northwind.Products
                        .Where("CategoryID = 3 AND UnitPrice > 3")
                        .OrderBy("SupplierID");


If you do not call ToList() and your final mapping to the DTO type, you can add Where clauses as you go, and build the results at the end:

var query = from u in DataContext.Users
where u.Division == strUserDiv 
&& u.Age > 18
&& u.Height > strHeightinFeet
select u;

if (useAge)
query = query.Where(u => u.Age > age);

if (useHeight)
query = query.Where(u => u.Height > strHeightinFeet);

// Build the results at the end
var results = query.Select(u => new DTO_UserMaster
{
Prop1 = u.Name,
}).ToList();

This will still only result in a single call to the database, which will be effectively just as efficient as writing the query in one pass.

I saw this answer here by Reed Copsey

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜