Home > database >  I have a LINQ query a Guid field ToString() is giving me error when is null
I have a LINQ query a Guid field ToString() is giving me error when is null

Time:01-28

I am calling a function to do a select in LINQ and the line UserKey = e.user_key.ToString(), is a GUID field that I convert to String and it is giving me an error when there are null fields, does anyone know how I can solve it?

internal static IQueryable<UserAccount> SelectDTO(this IQueryable<UserAccount> query)
        {
            return query.Select(e => new UserAccount()
            {
                Id = e.user_id,
                FirstName = e.first_name,
                LastName = e.last_name,
                MiddleInt = e.middle,
                UserKey = e.user_key.ToString(),
               
            });
        }

CodePudding user response:

You can use the Convert.ToString() method:

internal static IQueryable<UserAccount> SelectDTO(this IQueryable<UserAccount> query)
{
    return query.Select(e => new UserAccount()
    {
        Id = e.user_id,
        FirstName = e.first_name,
        LastName = e.last_name,
        MiddleInt = e.middle,
        UserKey = Convert.ToString(e.user_key),
       
    });
}

Since Convert.ToString() handles null, while ToString() doesn't.

Convert.ToString() doesn't need to presume the object is not null (as it is a static method on the Convert class), but instead will return String.Empty if it is null.

CodePudding user response:

The simplest thing is to use the "Elvis" operator.

Here how:

var guid = (Guid?)null;
var text = guid?.ToString();
Console.WriteLine(text == null);

That operator say, if the variable is null then return null, but otherwise call the .ToString() method.

That prints out True on the console.

So, in your code, it would look like this:

internal static IQueryable<UserAccount> SelectDTO(this IQueryable<UserAccount> query)
{
    return query.Select(e => new UserAccount()
    {
        Id = e.user_id,
        FirstName = e.first_name,
        LastName = e.last_name,
        MiddleInt = e.middle,
        UserKey = e.user_key?.ToString(),
    });
}

Yes, it's just the addition of a ?.

CodePudding user response:

assuming UserKey is a string type, try this

 UserKey = e.user_key==null? "" : e.user_key.ToString()

or if you are using net 6 with nullables

UserKey = e.user_key==null? "" : ((Guid) e.user_key).ToString()
  •  Tags:  
  • Related