0

I have a table called Employee. Some of the fields in the table are CompanyId, SomeData

I want to query the Min SomeDate based on a companyId.

Something like this:

public DateTime? GetMinDateForCompany(long CompanyId)
{
         dataContext.Employees.Where(emp => emp.CompanyID == companyId).Select(emp => emp.SomeDate).Min();

}

If there is no matching companyId, would it throw an exception. Is there a possibility that null could be returned. In general when would nulls be returned for a LINQ-to-SQL query.

2
  • 3
    You should try it and see - just call the method with a CompanyID you know doesn't exist and see what happens. Commented Jul 8, 2011 at 14:36
  • I agree with @Jon. Something like this you could have tested very quickly for yourself. Calling Max/Min/etc with no elements causes an InvalidOperationException: console.WriteLine(New List(Of Int16)() From {}.Max(Function(n) n > 0)) Commented Jul 8, 2011 at 14:48

2 Answers 2

2

You should call the Any() method to make sure you have results. Otherwise, you'll be calling Min() on no results, which will throw an error.

public DateTime GetMinPayrollDateForCompany(long CompanyId)
{
    if (dataContext.Payrolls.Any(proll => proll.CompanyID == companyId))
        return dataContext.Payrolls.Where(proll => proll.CompanyID == companyId).Select(proll => proll.PayrollDate).Min();
    else
        return new DateTime();

}

To answer your questions, I do believe that a query that has no results for companyId will throw an error. The Any() method will be your friend. Calling other methods on empty sets will throw errors.

Sign up to request clarification or add additional context in comments.

1 Comment

Not "Probably". It does cause an error. As with the OP, test it ;-)
0

Min will return NULL in SQL. This is expected. The problem arises in C# when you cast the result. if the type is non-nullable, you will get an error like the following:

The null value cannot be assigned to a member with type System.DateTime which is a non-nullable value type.

This is because C# will base the return type on the field you are asking for Min, in this case a DateTime (this is how generics works). But, we can avoid this error by simply typecasting the result to the nullable version of the type!

Your original query would change to the following:

dataContext.Payrolls
   .Where(proll => proll.CompanyID == companyId)
   .Min(proll => (DateTime?)proll.PayrollDate)

This will give a NULL result instead of throwing an exception. IIRC, if your original type is already nullable, you will not need the typecast.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.