I am designing a project on ASP.NET MVC 3.
I am using this query in my controller:
int batchSize = (int)db.ProductFormulation
.Where(r => r.ProductID =开发者_JS百科= p)
.Min(r => r.Quantity);
Where p is input by the user.
When i run my project and user enter a value of p which does not exist in my table then an error occurrs.
How can i stop this error, e.g a message box should be created that states there does not exist record for value you entered, and my project should run continuously.
Please suggest me what should i do for it. Thanks in advance.
You're getting an error because Min
is operating over a sequence with no elements.
You're basically looking for MinOrDefault()
, which doesn't exist in the LINQ framework.
This answer has a good implementation of how to achieve it.
Alternatively, if you don't want to do the aggregate operation server-side, you could materialize the sequence first then perform the min:
int batchSize = 0;
var results = db.ProductFormulation.Where(r => r.ProductID == p).ToList();
if (results.Count > 0)
batchSize = results.Min(x => x.Quantity);
Obviously if you've got a lot of records, the above isn't really suitable, and you're better off with the aforementioned extension method.
精彩评论