Oppdal
Oppdal

Reputation: 611

Minimalist LINQ approach - System.NullReferenceException

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();

Upvotes: 5

Views: 817

Answers (1)

dtb
dtb

Reputation: 217263

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();

Upvotes: 9

Related Questions