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();
                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();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With