简体   繁体   English

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

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

I am working on Linq to sql . 我正在使用Linq to sql I have created a function to search records in database. 我创建了一个功能来搜索数据库中的记录。 My functions is : 我的职能是:

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

I am trying to handle the case where if any one property out of Name, Date and Country is null. 我正在尝试处理Name, Date and Country任何一个属性为null的情况。 In that case i just want to remove that filter and fetch records only on the basis of non-null properties.I don`t want to add if - else conditions. 在那种情况下,我只想删除该过滤器并仅基于非null属性获取记录。我不想添加if-else条件。 How can i do this ? 我怎样才能做到这一点 ?

Since LINQ uses a Fluent interface you could do something like: 由于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;
}

I'm pretty sure this results in a less optimal SQL Query sent to the database, but it's just to illustrate the usage of fluent api in this matter. 我很确定这会导致发送给数据库的SQL查询的优化程度降低,但这只是为了说明流利的api在此问题上的用法。

You could also cheat with ?? 你也可以用??作弊 , like: , 喜欢:

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;
}

This should do the trick for you, basically you're going to say that if the parameter value is null OR the parameter value equals the row value then return me that row. 这应该为您解决问题,基本上,您将要说的是, 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