0

I get a null reference error when assigning anonymous type data to the dto property.

DTO is basically contains string ProductName, DateTime ProductDate

I am writing a linq query to assign data to these fields:

...
action = new
{
    Id = (Guid?)paa.Id ?? null,    
    Product= (from p in cx.Products
            join s in cx.Station on p.Id equals s.ProductId
            where p.IsDeleted == false
                && p.PlanStartDate != null                
                && p.IsDeleted == false
            select new
            {
                p.PlanStartDate,
                p.Code
            }
            ).FirstOrDefault(),                               
}

And some group rules. After that, i want to assign this property.

ProductDate= s3.Key.action.Product.PlanStartDate,
ProductCode= s3.Key.action.Product.Code,

But I'm getting nullreferenceexception. However, when I only use PlanStartDate property, everything is fine. But I cant solve this.

Samet Öz
  • 91
  • 1
  • 5
  • Most likely `FirstOrDefault` is returning `null` since there are no items where `IsDeleted == false`. – Lee Feb 29 '20 at 12:23
  • Hi @Lee As i say, when just select PlanStartDate, it's okey. Should i put the condition about, Code IsDeleted == false ? – Samet Öz Feb 29 '20 at 12:27
  • Sorry, I thought you meant you only used the `p.PlanStartDate != null` condition in the `where` clause. It's possible that `Product.Code` is null but the easiest way for you to fix this is attach a debugger and inspect the result. – Lee Feb 29 '20 at 12:34
  • Thanks for reply @Lee But, in my scenario if PlanStartDate not null, Code is always has a value. It's maybe orderby clause problem. But I can't figure it out. :( – Samet Öz Feb 29 '20 at 12:40

0 Answers0