Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimalist LINQ approach - System.NullReferenceException

Tags:

c#

linq

I'm wondering if it's possible to get this working:

product.PrimaryImage = db.ProductImages
    .Where(p => p.Product.ID == product.ID)
    .OrderBy(p => p.Order ?? 999999)
    .ThenBy(p => p.ID)
    .FirstOrDefault()
    .Name;
db.SaveChanges();

It works until there are no more images for that product at which point it throws...

System.NullReferenceException: Object reference not set to an instance of an object.

I made a fix for it but I'd prefer to keep it as minimal as possible and stay in Linq so was hoping there was a way to get my initial statement to function.

The ugly fix:

ProductImages primaryProductImage = db.ProductImages.Where(p => p.Product.ID == product.ID).OrderBy(p => p.Order ?? 999999).ThenBy(p => p.ID).FirstOrDefault();
string primaryImage = (primaryProductImage != null) ? primaryProductImage.Name : null;
product.PrimaryImage = primaryImage;
db.SaveChanges();
like image 694
Oppdal Avatar asked Nov 25 '11 17:11

Oppdal


1 Answers

Try this:

product.PrimaryImage = db.ProductImages
    .Where(p => p.Product.ID == product.ID)
    .OrderBy(p => p.Order ?? 999999)
    .ThenBy(p => p.ID)
    .Select(p => p.Name)
    .FirstOrDefault();
like image 147
dtb Avatar answered Sep 30 '22 09:09

dtb