0

I notice that all properties of my object that are leaving blank on client-side are staying null on server-side when binded.

This will eventually raise null object exception while doing some LINQ Where condition later on since the string property is null instead of empty.

I already try to add a CustomMetadataProvider with context.DisplayMetadata.ConvertEmptyStringToNull = false; as dicuss here ModelBinding but with no luck.

 providers = await dbData.Providers.AsNoTracking().
                OrderBy(order)
                .Where(q =>
            (query.search == null ||
            q.No.ToString().Contains(query.search) ||
            q.Name.Contains(query.search) ||
            q.Address.Contains(query.search) ||
            q.PhoneFax.Contains(phoneQuery) ||
            q.PhoneNumber.Contains(phoneQuery) ||
            q.PhoneTollFree.Contains(phoneQuery)) && (query.getDeleted || !q.Deleted))
            .Skip((query.limit * (query.page - 1))).Take(query.limit)
                .AsNoTracking().ToArrayAsync();
Pilouk
  • 1,267
  • 1
  • 18
  • 36

1 Answers1

2

The string should either be non-nullable or you should handle the null case. In your database, the backing column will either be set as NULL or NOT NULL, depending on whether you add the [Require] attribute to the property or not. If it is not required, then NULL is a perfectly acceptable value, and even arguably the best value, since it explicitly indicates "unset" rather than "set to an empty string".

Long and short, if you have a nullable property you want to query on, check for null values first:

(q.Name != null && q.Name.Contains(query.Search)) ||
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • I knew this solution but I wonder why with the previous web API and EF I didn't have to handle this. – Pilouk Mar 16 '18 at 17:34
  • Calling `Contains` on something like `q.Name` if it's null was always a problem. That's a simple language-level exception that there's no way around. If you weren't having issues previously, then the only explanation is that those columns were all NOT NULL in the previous iteration. – Chris Pratt Mar 16 '18 at 17:58