C# 实体框架-无法创建类型为的常量值

C# 实体框架-无法创建类型为的常量值,c#,linq,entity-framework,C#,Linq,Entity Framework,我读过关于这方面的其他问题,但我似乎无法理解 我有两个表,它们之间有一个链接表,如下所示: 组织(组织ID、名称) 扇区(扇区ID,名称) 组织/部门(组织ID、部门ID) 为什么会失败: public static void CalculateStats(int sectorId) { using (var db = new HContext()) { var sector = db.Sectors.Find(sectorId); IQuerya

我读过关于这方面的其他问题,但我似乎无法理解

我有两个表,它们之间有一个链接表,如下所示:

组织(组织ID、名称)
扇区(扇区ID,名称)
组织/部门(组织ID、部门ID)

为什么会失败:

public static void CalculateStats(int sectorId)
{
    using (var db = new HContext())
    {
        var sector = db.Sectors.Find(sectorId);
        IQueryable<int> orgIds = db.Organisations
            .Where(c => c.Sectors.Contains(sector) && 
            !l.IsInternational).Select(d => d.OrganisationID);

        // the exception occurs on the following line when
        // trying to make use of 'orgIds'
        var sections = db.Sections.Where(c => orgIds.Contains(c.OrganisationID) &&
            c.IsVerified).ToList();
    }
}
publicstaticvoidcalculatestats(intsectorid)
{
使用(var db=new HContext())
{
var sector=db.Sectors.Find(sectorId);
IQueryable orgIds=db.Organizations
其中(c=>c.扇区。包含(扇区)和
!l.IsInternational)。选择(d=>d.OrganizationID);
//以下行中出现异常:
//试图利用“orgIds”
var sections=db.sections.Where(c=>orgIds.Contains(c.organizationid)&&
c、 已验证)。ToList();
}
}
(希望它不会与任意实体名称混淆。扇区!=节。)


引发的异常是
无法创建“H.Data.Sector”类型的常量值。在此上下文中只支持基元类型或枚举类型。

您应该将基元类型传递给
Contains
方法,因此您不能传递那里的
扇区
实体。考虑按扇区ID检查:

IQueryable<int> orgIds = db.Organisations
   .Where(o => o.Sectors.Any(s => s.SectorId == sectorId) && !o.IsInternational)
   .Select(o => o.OrganisationID);
IQueryable orgIds=db.orgIds
其中(o=>o.Sectors.Any(s=>s.SectorId==SectorId)和&!o.IsInternational)
.选择(o=>o.OrganizationID);

工作正常。感谢您的快速回复:)可能重复的