Home > Software design >  Set value to a field in LINQ with logical expression
Set value to a field in LINQ with logical expression

Time:01-30

I'm making a program for teacher to control students' practice lessons. I need to set value like "Has report" if field has anything and "No report" if field is null or empty.

I have the following code:

C#

var record = from results in _context.Results
                             join students in _context.Students on results.Student_Id equals students.Id
                             join practice in _context.Practice on results.Theme_Id equals practice.Id
                             join gr in _context.Groups on students.Group_Id equals gr.Id
                             where gr.Title == group_selected
                             select new
                             {
                                 Theme = practice.Title,
                                 Student = students.Name,
                                 Report = results.File.IsNullOrEmpty() ? "No report" : "Has report"
                             };

But it gives me error:

"System.Data.SqlTypes.SqlNullValueException" in Microsoft.EntityFrameworkCore.Relational.dll Error message: Undefined data. This method or property cannot be called for null values.

Please, help :)

CodePudding user response:

Going off the assumption that results.File is a nullable NCHAR/ NVARCHAR in a Sql Server, in the null case, you would be doing DBNull.IsNullOrWhitespace(). This is not a defined extension method of DBNull.

I would write this null check as:

Report = string.IsNullOrWhiteSpace(results.File as string) ? "No report" : "Has report"

I hope this fixes the issue

  • Related