Reputation: 2616
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"
:
Here's my LINQ. I'm trying to select out the columns in the order I need them & concatanate them into 1 string:
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. I just want the values of the strings. Is there a way to achieve this?
Upvotes: 0
Views: 829
Reputation: 21487
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();
Upvotes: 0
Reputation: 62488
linq query will return a collection, you have to use First()
or FirstOrDefault()
to get the item :
string queryResult = query.FirstOrDefault().sqlQuery;
better is to check for null as well:
string queryResult = query.FirstOrDefault() != null ? query.FirstOrDefault().sqlQuery : string.Empty;
Upvotes: 2