Naveed Ullah
Naveed Ullah

Reputation: 621

Why Receiving Null through LINQ?

why part 2 is returning null.

the strange part is that if i search by string type then null returns, but if i search by integer type or bool type. then i get brand object.

Part 1

//....     OK code
                 public static Brand GetBrand(string name)
                {
                    DataContext db = new DataContext();
                    using (db)
                    {
                        Brand b = (from v in db.Brands
                                   where v.Name == name
                                   select v).FirstOrDefault();
                        return b;
                    }
                }




               [HttpGet]
               public IHttpActionResult Get(string name)
               {
                   Brand b = MobileHandler.GetBrand(name);
                   return Ok(b);
               }

Part 2

//.....   Return null
       public static List<Brand> GetBrands()
            {
                DataContext db = new DataContext();
                using (db)
                {
                    return db.Brands.ToList();
                }
            }

           [HttpGet]
           public IHttpActionResult Get(string name)
           {
               return Ok((from v in MobileHandler.GetBrands()
                          where v.Name == name
                          select v).FirstOrDefault());
           }

But I get the following error:

<Brand xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DataLayer.MobileMgt" i:nil="true"/>

Upvotes: 0

Views: 105

Answers (1)

Euphoric
Euphoric

Reputation: 12849

I believe this is issue of case-sensitive comparison. This is indicated by your code working for ints and bools and not strings and by a fact that brand name is "Apple" not "apple"

Entity Framework uses case comparison settings on the SQL server, which is usually set to be case-insensitive. In your case then "Apple" is equals to "apple". This is the first case.

But .NET uses case-sensitive comparison, which is the second case. So "apple" wont be equal to "Apple". To fix this instead of v.Name == name use v.Name.Equals(name, StringComparison.OrdinalIgnoreCase).

Upvotes: 1

Related Questions