繁体   English   中英

如何使用linq-to-sql从数据库访问记录?

[英]How to access record from database using linq-to-sql?

我正在使用Linq to sql 我创建了一个功能来搜索数据库中的记录。 我的职能是:

    public IEnumerable<Record> SearchRecord()
    {
      var records = db.Records.Where(r => r.Name == Name && r.Date == Date 
                                                && r.Country == Country);
        return records;
    }

我正在尝试处理Name, Date and Country任何一个属性为null的情况。 在那种情况下,我只想删除该过滤器并仅基于非null属性获取记录。我不想添加if-else条件。 我怎样才能做到这一点 ?

由于LINQ使用Fluent界面,因此您可以执行以下操作:

public IEnumerable<Record> SearchRecord()
{
    var records = db.Records;
    if (Name != null)
    {
        records = records.Where(r => r.Name == Name);
    }
    if (Date != null)
    {
        records = records.Where(r => r.Date == Date);
    }
    if (Country != null)
    {
        records = records.Where(r => r.Country == Country);
    }
    return records;
}

我很确定这会导致发送给数据库的SQL查询的优化程度降低,但这只是为了说明流利的api在此问题上的用法。

你也可以用??作弊 , 喜欢:

public IEnumerable<Record> SearchRecord()
{
    var records = db.Records.Where(r => r.Name == (Name ?? r.Name)
                                        && r.Date == (Date ?? r.Date)
                                        && r.Country == (Country ?? r.Country));
    return records;
}

这应该为您解决问题,基本上,您将要说的是, if the parameter value is null OR the parameter value equals the row value then return me that row.

public IEnumerable<Record> SearchRecord()
{
    var records = db.Records.Where(r => (Name == null || r.Name == Name)
                                        && (Date == null || r.Date == Date)
                                        && (Country == null || r.Country == Country));
    return records;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM