简体   繁体   English

从Linq查询结果构建原始SQL字符串?

[英]Building a Raw SQL String from Linq Query Results?

I need to make a selection from a SQL Server table and concatenate the results into a SQL string so I end up with var sqlString = "Select blah from myTable where blah blah order by blah" : 我需要从SQL Server表中进行选择,并将结果连接到SQL字符串中,所以最终得到var sqlString = "Select blah from myTable where blah blah order by blah"

在此处输入图片说明

Here's my LINQ. 这是我的LINQ。 I'm trying to select out the columns in the order I need them & concatanate them into 1 string: 我正在尝试按需要的顺序选择列并将它们合并为1个字符串:

  var query = (from a in _Context.tbArticleTypeAssets
                      where a.ArticleType == ArticleType
                      select new {sqlQuery = a.ColSelection + "" + a.FromTable + "" + a.whereclause + "" + a.orderBY});

         string queryResult = query.ToString();

The result is a Linq output which I don't want. 结果是我不想要的Linq输出。 I just want the values of the strings. 我只想要字符串的值。 Is there a way to achieve this? 有没有办法做到这一点?

linq query will return a collection, you have to use First() or FirstOrDefault() to get the item : linq查询将返回一个集合,您必须使用First()FirstOrDefault()来获取项目:

 string queryResult = query.FirstOrDefault().sqlQuery;

better is to check for null as well: 更好的是也检查null:

string queryResult =  query.FirstOrDefault() != null ? query.FirstOrDefault().sqlQuery : string.Empty;

Try this: 尝试这个:

 var query = _Context.tbArticleTypeAssets
        .Where(a=>a.ArticleType == ArticleType)
        .Select(a=>a.ColSelection + "" + a.FromTable + "" + a.whereclause + "" + a.orderBY)
        .ToList();

or if your query will always only return one record, then you can do this: 或者,如果您的查询始终只返回一条记录,则可以执行以下操作:

 var query = _Context.tbArticleTypeAssets
        .Where(a=>a.ArticleType == ArticleType)
        .Select(a=>a.ColSelection + "" + a.FromTable + "" + a.whereclause + "" + a.orderBY)
        .First();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM