[英]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. 我为它做了一个修复,但我宁愿尽量保持它并留在Linq所以希望有一种方法可以使我的初始语句起作用。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.