I am using linq to get some data from my database. When query is empty I want to throw an exception.
public class LinqDataBaseConnector : IDataBaseConnector
{
public LinqDatabaseDataContext dataContext;
public User getUser(string login, string password)
{
var query = (from c in dataContext.Users
where c.username == login && c.password == password
select c);
if (query.Any())
{
return query.First();
}
else
{
throw new NullReferenceException("Empty query!");
}
}
public HardwareConfiguration getHardwareConfiguration(int id)
{
var query = (from c in dataContext.HardwareConfigurations
where c.ID == id
select c);
if (query.Any())
{
return query.First();
}
else
{
throw new NullReferenceException("Empty query!");
}
}
}
How to extract this if/else to ONE private method. Do I need to implement IQueryable<T> interface ?
NullReferenceExceptioninstead throwInvalidArgumentExceptionquery.First()will already throw an exception if the query is empty - why not just use that?Single()rather thanFirst()First.