无法在LINQ实体VS 2017中使用包含在我的查询中

问题描述 投票:0回答:2

我的查询是,

我在这里试图获取与区域名称匹配的区域ID,

var Rid = db.Regions.Where(p => SqlFunctions.PatIndex("%" + Search + "%", p.RegionName) > 0).Select(p => p.RegionId).ToList();

以字符串分隔的更改ID的逗号,

string joined = string.Join(",", Rid);

试图获取与ID逗号有关的所有记录,并以string joined分隔

var employ = db.Employees.Include(f => f.City).Include(f => f.Region).Where(p=>p.RegionId);

问题是,当我尝试在where子句中使用时,我们没有包含??

希望您的建议

c# linq asp.net-mvc-5 linq-to-entities where-clause
2个回答
1
投票

在Linq中,我们有Any

var employ = db.Employees.Include(f => f.City)
                         .Include(f => f.Region)
                         .Where(p=> Rid.Any(rid => rid == p.RegionId));

或:

var employ = db.Employees.Include(f => f.City)
                         .Include(f => f.Region)
                         .Where(p=> Rid.Contains(p.RegionId));

现在,它将选择在Rid列表中具有区域ID的那些雇员。


0
投票

您应该使用虚拟属性映射关系:

public class Employee
{
    ...

    public int RegionId { get; set; }
    [ForeignKey("RegionId")]
    public virtual Region Region { get; set; }

    ...
}

然后您可以直接在where语句中使用它:

var employees = db.Employees.Where(a => a.Region.RegionName.Contains(Search));

这样,您发送较少的数据来进行查询,请考虑选择100个区域ID的情况。另外,您正在执行1个查询,而不是2个。

© www.soinside.com 2019 - 2024. All rights reserved.