0

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":

enter image description here

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?

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Great, thanks. Why do I get 'sqlQuery = SELECT blah blah' in my result? On the Select new I have to give a name but I don't want the name to appear in the resulting string?
@Hardgraf the way I posted should not give you like that, and you can skip new which is creating anonymous object actually
I mean like : select a.ColSelection + "" + a.FromTable
0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.