C#Linq查询作为函数参数

时间:2015-02-11 19:51:26

标签: c# linq

我正在使用linq从我的数据库中获取一些数据。当查询为空时我想抛出异常。

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!");
        }
    }
}

如何将此if / else提取为一个私有方法。我需要实现IQueryable<T>接口吗?

4 个答案:

答案 0 :(得分:8)

请勿拨打Any,只需致电First。如果查询没有项目,它将抛出异常,这正是您想要的。由于First已经具有适当的语义,因此无需创建另一个运算符。

除了更容易之外,它还导致数据库查询只执行一次,而不是两次。

答案 1 :(得分:1)

以下简化代码。我也希望你有一些密码哈希而不仅仅是纯文本。

public class LinqDataBaseConnector : IDataBaseConnector
{
    #region Private Variables
    public LinqDatabaseDataContext dataContext;
    #endregion

    public User getUser(string login, string password)
    {   
        return this.dataContext.Users.First(x => x.username == login && x.password == password);
    }

    public HardwareConfiguration getHardwareConfiguration(int id)
    {   
        return this.dataContext.HardwareConfigurations.First(x => x.ID == id);
    }
}

答案 2 :(得分:0)

为什么不

    var query = (from c in dataContext.Users
                 where c.username == login && c.password == password
                 select c).FirstOrDefault();

    if (query!=null)
    {
        return query;
    }
    else
    {
        throw new NullReferenceException("Empty query!");
    }

答案 3 :(得分:0)

有什么理由不能将它作为扩展方法实现:

public static class Extensions
{
    public static T GetFirstOrException<T>(this IEnumerable<T> myList)
    {
        if (myList.Any())
        {
            return myList.First();
        }
        else
        {
            throw new NullReferenceException("Empty query!");
        }
    }
}

在这两种情况下,您都可以使用扩展方法:

public User getUser(string login, string password)
{
    var query = (from c in dataContext.Users
                 where c.username == login && c.password == password
                 select c);

    return query.GetFirstOrException();
}

public HardwareConfiguration getHardwareConfiguration(int id)
{
    var query = (from c in dataContext.HardwareConfigurations
                 where c.ID == id
                 select c);

    return query.GetFirstOrException();
}