locked
How to return a empty object when linq query yields nothing (null) instead of null. RRS feed

  • Question

  • I'm trying to query the database using linq query and the FirstOrDefault yields null value.

    Is there a way I can return a empty object instead of null?

    API call:

    [HttpGet]
            [Route("userprofessionalinfo/{userGuid}")]
            public IHttpActionResult GetUserProfessionalInfo(Guid userGuid)
            {
                var context = new BuffiniCodeBehindBusinessLogicProfile();
                var userProfessionalData = context.GetUserProfessionalData(userGuid);            
                var userSocialMediaData= context.GetUserSocialMediaData(userGuid);
                var userDesignationData = context.GetUserDesignationData(userGuid);
                return Ok(new { userProfessionalData, userSocialMediaData, userDesignationData });
            }


    ViewModel:

     public class ProfessionalInfoViewModel
        {
            public Guid UserGUID { get; set; }
            public ProfessionalDataModel ProfessionalInfo { get; set; }
    
        }


    BusinessLogic:

    public ProfessionalInfoViewModel GetUserProfessionalData(Guid userGuid)
            {
                using (var ctxAdmin = new SignInDataContext(ConfigurationManager.ConnectionStrings[Constants.CONFIG_KEY_SIGNIN_CONNECTION_STRING].ToString()))
                {
                    var model = (from up in ctxAdmin.User_Professional_Infos
                                 select new ProfessionalInfoViewModel
                                 {
                                     UserGUID = up.user_guid,
                                     ProfessionalInfo = new ProfessionalDataModel
                                     {
                                         AssociationId = up.association_id,
                                         ProfessionalBio = up.professional_bio,
                                         StateCode = up.association_state_code
                                     }
                                 }).FirstOrDefault(x => x.UserGUID == userGuid);
                    return model;
                }
            }

    The same way all the three call return null values, I need to pass in a empty object instead of null to my Angular 8 client, failing which I get below error in my console.log


    I appreciate your time in helping me out. Thanks.


    Email address update for alerts

    Monday, October 21, 2019 3:08 AM

All replies

  • Hi Anantha Asamani, 

    Thank you for posting here.

    You can define 'nothing' in ‘ProfessionalInfoViewModel’.

    I make a  test on my side, and you can refer to it.

        class Program
        {
            static void Main(string[] args)
            {
                teacher t = method1();             
                Console.ReadLine();
            }
            static teacher method1()
            {
                List<student> lst = new List<student>(){
                    new student(){ id = 1,name = "A"},
                    new student(){ id = 2,name = "B"},
                    new student(){ id = 3,name = "BB"},
                    new student(){ id = 4,name = "D"},
                    new student(){ id = 7,name = "E"}
                };
                List<teacher> tLst = new List<teacher>();
                var result = (from value in lst
                              select new teacher
                              {
                                  tId = value.id,
                                  tName = value.name
                              }).FirstOrDefault(x => x.tId == 5);
                teacher teacherNull = new teacher() { tId = 0, tName = ""};
                return result == null ? teacherNull : result;
            }
        }
        class student
        {
            public int id { get; set; }
            public string name { get; set; }
        }
        class teacher
        {
            public int tId { get; set; }
            public string tName { get; set; }
        }

    Result of my test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 21, 2019 8:48 AM
  • Hi Xingyu Zhao,

    First of allthanks for the reply, I appreciate your time.

    I was searching for a approach online and I found one of the statement as below in one of the blog,

    The only thing you should not do:

    • return an "empty" instance of the class.

    https://softwareengineering.stackexchange.com/questions/352387/null-or-empty-object-when-linq-to-entities-query-returns-nothing

    I'm not sure about the reason, so I continued my solution search.

    Please let me know if you have any thoughts on this.

    Thanks.


    Email address update for alerts

    Monday, October 21, 2019 2:33 PM
  • Hi Ananth,

    I'm guessing you need to do the work on the front end for this situation.

    The javascript to read this should be:

    let data = (data that comes back from the api) || {};
    let professionalInfo = data.ProfessionalInfo || null; // or {} if you prefer to use an empty object.  That's what I'd do.

    Or simply:

    let data = (data that comes back from the api) || { ProfessionalInfo: {} }; 

    This will safely return the ProfessionalInfo object to you whether or not the data is returned via the api.  Then if you make it an empty object, then any property inside of ProfessionalInfo won't break either.

    Hope that helps.
    Monday, October 21, 2019 5:14 PM
  • Hi Anantha Asamani,

    The reference you provided suggestes that you should handle "empty" instance of the class.

    As suggested in the reference, you can use the following code.

                var result = (from value in lst
                              select new teacher
                              {
                                  tId = value.id,
                                  tName = value.name
                              }).FirstOrDefault(x => x.tId == 5) ?? new teacher(); ;
                return result;

    Result:

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, October 23, 2019 9:22 AM
  • Hi Josh,

    Thanks for the reply, I did follow your suggestion and used it the below way but no luck.

    this.profileService.getUserInfo(this.userGuid).subscribe( // To Do: get the user id from other source
                data => {
                    
                    this.userInfo = data || {} as IUserInformation;
                    console.log(this.userInfo);
                    let jsonString = JSON.stringify(data);
                    let jsonPar = JSON.parse(jsonString);
                    
                    this.DateOfBirth.year = new Date(jsonPar.DateOfBirth).getFullYear();
                    this.DateOfBirth.month = new Date(jsonPar.DateOfBirth).getMonth() + 1;
                    this.DateOfBirth.day = new Date(jsonPar.DateOfBirth).getDate();
                    
                },
                error => this.errorMessage = <any>error
            );

    

    I'm literally clue less, dead in the water.
    Please help me out.



    Email address update for alerts

    Thursday, October 24, 2019 5:43 PM