I try to get datas from database. I need to get first product's image url ordered by the lowest position. Action is running on Index view where I have 20 records per page. Code to get image url with first position:
var firstImage = productImageRepository.Get().Where(i => i.ProductId == productId).OrderBy(i => i.Position).First();
In my database only products with id 1-7 have images. When the loop is on product with id 8 and higher, I'm getting and error:
Is there possibility to check if this product's image exists in database? I know I can equal it to some value and check it like if (firstImage != null), but I don't know how to do this without equal position to any value.
use FirstOrDefault()
, it is just like First()
except that if no element match the specified condition than it returns the default value of the underlying type of generic collection.
You can then check if the value is defined which tells you if any items exist in the database, in your case FirstOrDefault()
will return null
if no images exist in the database.
You can also use Any()
with First()
as well
My solution would be
var images = productImageRepository.Get().Where(i => i.ProductId == productId).OrderBy(i => i.Position);
if (images.Any()) {
// could just use First() here now if you wanted
// as Any() confirms there is values defined
return Json(images.FirstOrDefault());
} else {
// throw a error or something.
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments