简体   繁体   English

在C#中的实体框架中选择“多字段”

[英]Select Multi fields in Entity framework in c#

I want to select 2 or more fields like this: for example we have a list of some people and now they say find people who is male and live in New York 我想选择2个或更多这样的字段:例如,我们有一些人的名单,现在他们说找到住在纽约的男性。
we have 2 fields in here "City" and "Sexual". 我们在这里有“城市”和“性”两个字段。

I can do it like this 我可以这样

private List<tblTest> GetAll(string city, string sexual)
{
    var all = (from x in db.tblTest
               where x.city == city && x.sexual == sexual
               select x).ToList();
    return all;
}

and this one is not helping: 而这个没有帮助:

private List<tblTest> GetAll(string city, string sexual)
{
    var all = (from x in db.tblTest
               where x.city == city || x.sexual == sexual
               select x).ToList();
    return all;
}

with " && " I can do it but if I want to just select " City " it is not working, and I want to search like this for 14 fields and we want to search for some fields not all fields we have and we don't know which fields we want to search 使用“ && ”,我可以做到,但是如果我只想选择“ City ”,那是行不通的,我想像这样搜索14个字段,我们想搜索某些字段,而不是我们拥有的所有字段,而我们却没有不知道我们要搜索哪些字段

What should I do? 我该怎么办?

The way I do is following: 我的方法如下:

private List<tblTest> GetAll(string city, string sexual)
{
    var query = db.tblTest.AsQueryable();
    if(!string.IsNullOrEmpty(city))
    {
        query = query.Where(x => x.city == city);
    }
    if(!string.IsNullOrEmpty(sexual ))
    {
        query = query.Where(x => x.sexual == sexual );
    }
    return all.ToList();
}

It is important to call AsQueryable otherwise it might be that, if you write IEnumerable<tblTest> query = ... , the result is queried more that 1 times. 调用AsQueryable非常重要,否则,如果您编写IEnumerable<tblTest> query = ... ,则查询的结果将超过1次。

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

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