Reputation: 5375
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.
Upvotes: 0
Views: 757
Reputation: 3122
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.
Upvotes: 0
Reputation: 3908
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.
Upvotes: 2