1

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 == 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.

RPM1984
  • 72,246
  • 58
  • 225
  • 350
Pushpendra Kuntal
  • 6,118
  • 20
  • 69
  • 119

1 Answers1

6

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
RPM1984
  • 72,246
  • 58
  • 225
  • 350