Ehsan Akbar
Ehsan Akbar

Reputation: 7301

EF can't return the items with condition but sql can why?

I have a query like this :

   int a= pgc.Fronts.Where(i => i.ItemCode == itemcode && i.PC == pc).Count()

PGC is my dbcontext .The itemcode is '10414' and the pc value is null the result is 0.

So i changed the query to sql command :

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT  [Id]
      ,[No]
      ,[ItemCode]
      ,[QtyRequest]
      ,[PC]
      ,[Date]
      ,[Type]
      ,[Line]
      ,[joint]
      ,[QTYIssue]
      ,[Recivedby]
  FROM [pgc].[dbo].[Fronts] where ItemCode='10414' and pc is null

it returns 3 records as you can see here :

enter image description here

So why it happens ?

 public partial class Front
    {
        public long Id { get; set; }
        public string No { get; set; }
        public string ItemCode { get; set; }
        public Nullable<double> QtyRequest { get; set; }
        public string PC { get; set; }
        public System.DateTime Date { get; set; }
        public string Type { get; set; }
        public string Line { get; set; }
        public string joint { get; set; }
        public double QTYIssue { get; set; }
        public string Recivedby { get; set; }
    }

Upvotes: 0

Views: 36

Answers (1)

Magnus
Magnus

Reputation: 46977

If I remember correctly (at least for Linq2Sql) if you want to compare with null values you should use Object.Equals:

int a = pgc.Fronts.Where(i => 
               i.ItemCode == itemcode && Object.Equals(i.PC, pc)).Count();

This "bug" seems to have been fixed in later versions of Entity framework. For now you can use:

int a = pgc.Fronts.Where(i => 
      i.ItemCode == itemcode && (i.PC == pc || (pc == null && i.PC == null)).Count();

Upvotes: 2

Related Questions