0

Hy,
I want to convert a sql command into linq, but I receive the message :

< Nullable object must have a value >

My sql query is:

 Select sum(PosList.Cantity) AS cant, sum(PosList.Value) as mysum,PosList.price,PosList.Name
 from list Inner join PosList On list.ID = PosList.FactID 
 WHERE     (list.FirID = 1) AND (PosList.Date BETWEEN '2011-02-22' AND '2012-02-22') 
 GROUP BY PosList.Name, PosList.Price ORDER BY Value DESC

My linq is:

    var w = (from item in list join itemPos in PosList   on item.ID equals itemPos.FactID      
  where item.FirID == this.firId && item.Date >= date_start && item.Date <= date_stop   
  group itemPos by itemPos.Name into hh   
  let mysum = hh.Sum(s => s.Value)    
  let cant = hh.Sum(n => n.Cantity)   
  let price = hh.Average(i => i.Price)                                  
  orderby mysum descending  
  select new Agent("", 0, 0, "", hh.Key, "", 0, (double)price, (double)cant, (double)mysum, 0, "", "", "", "", ""));

I tried the following linq, but it did not work:

 var w = (from item in list
 join itemPos in PosList  on item.ID equals itemPos.FactID   
 where item.FirID == this.firId && item.Date >= date_start && item.Date <= date_stop   
 group itemPos by itemPos.Name into hh   
 let mysum = hh.Sum(s => s.Value)                    
orderby mysum descending  
 select new Agent("", 0, 0, "", hh.Key, "", 0, (double)hh.Average(i =>i.Price), (double)hh.Sum(n =>n.Cantity), (double)mysum, 0, "", "", "", "", ""));   

The only linq which works ok is:

   var w = (from item in list
    join itemPos in PosList
   on item.ID equals itemPos.FactID   
    where item.FirID == this.firId && item.Date >= date_start && item.Date <= date_stop   
    group itemPos by itemPos.Name into hh   
   let mysum = hh.Sum(s => s.Value)                    
   orderby mysum descending  
  select new Agent("", 0, 0, "", hh.Key, "", 0, 0, 0, (double)mysum, 0, "", "", "", "",""));   

but I need those two values(price and cantity) also..
Thanks !

1
  • the problem is if I want to add the Price and Cantity fields in the linq the error: Nullable object must have a value appairs and I dont know what am I missing. Commented Feb 23, 2012 at 13:40

1 Answer 1

1

So the part (double)hh.Average(i =>i.Price), (double)hh.Sum(n =>n.Cantity) causes the exception. Which means that you must add conditions to get the records where Price is not null and Cantity is not null. And add i.Price.Value and n.Cantity.Value.

(Maybe this applies to Price or Cantity only, but I cannot tell that from your code).

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! this was the problem: I had some null fields for price

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.