Home > Enterprise >  in Linq replace null to empty
in Linq replace null to empty

Time:01-24

var ch = _context.xxtu_nintex_emp_data_v
         .Where(o => o.LOGIN_USER_NAME ==userId.ToUpper())
         .Select(emp => new
         { OTHERMOBILENO = emp.OTHERMOBILENO ?? "" })
         .ToList().SingleOrDefault();

the result is

enter image description here

when use toList() I get what I want but it is so slow

var ch = _context.xxtu_nintex_emp_data_v.ToList()
         .Where(o => o.LOGIN_USER_NAME ==userId.ToUpper())
         .Select(emp => new
         { OTHERMOBILENO = emp.OTHERMOBILENO ?? "" })
         .ToList().SingleOrDefault();

the result is

enter image description here

I use code first approach api and Microsoft.EntityFrameworkCore

CodePudding user response:

Some things you could try

  1. Call ToList after the condition, to only fetch a subset of data from the Database

     var ch = _context.xxtu_nintex_emp_data_v
          .Where(o => o.LOGIN_USER_NAME == userId.ToUpper())
          .ToList() //<-- here
          .Select(emp => new
          { OTHERMOBILENO = emp.OTHERMOBILENO ?? "" })
          .ToList().SingleOrDefault();
    
  2. Move the Select after the Last ToList call

     var ch = _context.xxtu_nintex_emp_data_v
          .Where(o => o.LOGIN_USER_NAME == userId.ToUpper())
          //<-- re-arrange ToList/Select
          .ToList()
          .Select(emp => new { OTHERMOBILENO = emp.OTHERMOBILENO ?? "" }) 
          //<-- 
          .SingleOrDefault();
    
  3. Re-arrange it a bit more

     var emp = _context.xxtu_nintex_emp_data_v
          .Where(o => o.LOGIN_USER_NAME == userId.ToUpper())
          .SingleOrDefault();
    
     var ch = new { OTHERMOBILENO = emp?.OTHERMOBILENO ?? "" };
    
  •  Tags:  
  • Related