EF/ASP Core handle string property as NULL instead of empty

asp.net-core asp.net-core-webapi entity-framework-core

Question

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();
1
0
3/16/2018 4:43:37 PM

Accepted Answer

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)) ||
1
3/16/2018 5:08:12 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow