none
About query single value from database table. RRS feed

  • Question

  • Hi all,

    I have a snippet like this:
                var id = from c in dataContext.Customers
                             where c.name == "xxx"
                             select c.id;

    So how can I check if the id is null (that means no record field returns). And if id has a value inside, how can I access it? (the id field in database is UniqueIdentifier type)

    Thank you very much.

    Best regards,
    Diviner.
    Tuesday, August 5, 2008 9:37 AM

Answers

  • In this case, id will be a IQueryable<Guid>. You have a couple options to see if a value exists. You can either see if id.Count()>0, or use FirstOrDefault() to return the first item for you to continue working with. It will return null if no items exist matching your criteria.

     

    Jim Wooley

    www.ThinqLinq.com

     

    Tuesday, August 5, 2008 1:13 PM
    Moderator

All replies

  • In this case, id will be a IQueryable<Guid>. You have a couple options to see if a value exists. You can either see if id.Count()>0, or use FirstOrDefault() to return the first item for you to continue working with. It will return null if no items exist matching your criteria.

     

    Jim Wooley

    www.ThinqLinq.com

     

    Tuesday, August 5, 2008 1:13 PM
    Moderator
  • Now I have a text box for user to type in a Customer Name, and I want to convert it to Customer ID in order to save it to some table, like this:
        Guid? customer_id = CustomerDAO.QueryIdByName(textboxCustomerName.Text));

    So I write a static method like this:
            public static Guid? QueryIdByName(String name)
            {
                var id = from c in dataContext.Customers
                         where c.name == name
                         select c.id;
                if (id.FirstOrDefault() != Guid.Empty)
                {
                    return id.First();
                }
                else
                {
                    return null;
                }
            }

    I think the code is a little bit tortuous, are there any code more
    intuition?

    --
    Best regards,
    Diviner.
    Thursday, August 7, 2008 1:38 AM
  • See if the following works for you:

     

    Code Snippet

     public static Guid? QueryIdByName(String name)
            {

                return (from c in dataContext.Customers
                         where c.name == name
                         select c.id).FirstOrDefault();
            }

     

     

    Jim Wooley

    www.ThinqLinq.com

    Thursday, August 7, 2008 1:42 AM
    Moderator
  • Jim Wooley,

    When there is no record followed the rule, FirstOrDefault( ) return Guid.Empty ( that is value {00000000-0000-0000-0000-000000000000}. But I want the field stay NULL instead of this empty guid.

    Any suggestion else?

    --
    Best regards,
    Diviner.
    Thursday, August 7, 2008 6:16 AM