尝试使用实体EF6获取行时出错

时间:2016-10-27 12:06:56

标签: c# .net entity-framework-6 linq-to-entities

我首先将linq用于实体6代码。

这是两个实体类:

    public class Site 
    {
        public int Id { get; set; }
        public int UID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? ContractId { get; set; }
        public int? SiteTypeId { get; set; }

        public virtual ICollection<SiteRegion> Regions { get; set; }
    }


    public class SiteRegion 
    {
        public int Id { get; set; }
        public int UID { get; set; }
        public int? SiteId { get; set; }
        public string Name { get; set; }
        public int? RegionTypeId { get; set; }

        [ForeignKey("SiteId")]
        public virtual Site Site { get; set; }

    }

正如您所见,Regions字段是约束,我在表之间有一对多的关系。

我已创建此LINQ查询以从Sites表中获取所需的行:

int?[] ContractId = [1,2];
int?[] siteTypeId = [1,2,3]; 

 var result = (from sites in context.Set<Site>()
               where contractsIDList.Contains(sites.ContractId) && 
               siteTypeId.Contains(sites.SiteTypeId) &&
               select sites).AsNoTracking<Site>();

它工作正常。

现在我有了新的要求,我需要在SiteRegion表中的RegionTypeId列中过滤我的查询这里是我的新查询:

int?[] ContractId = [1,2];
int?[] siteTypeId = [1,2,3]; 
int?[] regionTypeId = [1,2,3];

 var result = (from sites in context.Set<Site>()
               where contractsIDList.Contains(sites.ContractId) && 
               siteTypeId.Contains(sites.SiteTypeId) &&
    regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())

               select sites).AsNoTracking<Site>();

但我得到错误:

Error   36  'int?[]' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains<TSource>(System.Linq.IQueryable<TSource>, TSource)' has some invalid arguments 

在这一行:

regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())

如何修复上面的查询以获取所需的行?

1 个答案:

答案 0 :(得分:1)

您需要按照以下所示进行操作。

注意:

错误regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())

正确: regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item))

工作样本:

 int?[] contractsIDList = { 1, 2};
 int?[] siteTypeId = { 1, 2, 3};
 int?[] regionTypeId = { 1, 2, 3};

var result = (from sites in db.Set<Site>()
              where contractsIDList.Contains(sites.ContractId) && siteTypeId.Contains(sites.SiteTypeId)
              && regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item))
              select sites).AsNoTracking<Site>();

结果:

enter image description here