2

I am trying to concatenate for a label. If a field contains null then entire concatenate result is null.

[HttpGet]
public ActionResult PMAByPC(string PartnerCode)
{
    var result = (from N in _POSContext.PMAs
                  where (N.PartnerCode == PartnerCode)
                  select new 
                  { 
                      label = N.Address1 + " | " + N.Address2 + " | " + N.City, 
                      id = N.ID 
                  });

    return Json(result);
}

Here, if data is not present in of the fields, label becomes null.

I tried with

select new { label = N.Address1 ?? "?" + " | " + N.Address2 ?? "?" + " | " + N.City ?? "?", id = N.ID }

then it takes only N.Address1 value and ignores the rest of the fields.

4
  • 1
    Does string interpolation i.e. new { label = $"{N.Address1}|{N.Address2}|{N.City}", id = N.ID } give the same results? learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
    – RemarkLima
    Sep 2, 2018 at 18:27
  • Its working...string interpolation is as expected in this case.
    – Ramesh
    Sep 2, 2018 at 18:36
  • String interpolation works because the expression is evaluated client side (C#).
    – Ivan Stoev
    Sep 2, 2018 at 18:38
  • General advice: 1) never return live queries to the MVC pipeline. 2) use the asynchronous features of Entity Framework Core. Sep 2, 2018 at 18:44

2 Answers 2

4

Looks like this is a standard SQL string concatenation behavior (the same happens with SqlServer database).

If you want to evaluate the concatenation server side (database), you need to convert null to empty string "" (or something else) using the ?? operator. Similar to your attempt, but you've missed the C# operator precedence. The way you wrote it is equivalent of

N.Address1 ??
(
  ("?" + " | " + N.Address2) ??
  (
      ("?" + " | " + N.City) ?? "?"
  )
)

which is not what was the intent.

You can avoid such issues by enclosing similar conversions with brackets:

select new
{
    label = (N.Address1 ?? "?") + " | " + (N.Address2 ?? "?") + " | " + (N.City ?? "?"),
    id = N.ID,
} 
0

This is the standard compliant and reasonable behavior: if you concatenate a string with an unknown string, the result is unknown.

Use the coalesce function for that:

coalesce(col1, '') || coalesce(col2, '')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.