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

时间:2014-01-01 21:21:05

标签: c# linq entity-framework

我已经阅读了有关此问题的其他问题,但我似乎无法想象......

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

组织(组织ID,姓名)
部门(部门ID,名称)
Organisations_Sectors(OrganisationID,SectorID)

为什么会失败:

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

(希望它不会与任意实体名称混淆。部门!=部分。)

抛出的异常是Unable to create a constant value of type 'H.Data.Sector'. Only primitive types or enumeration types are supported in this context.

1 个答案:

答案 0 :(得分:3)

您应该将基本类型传递给Contains方法,因此您无法在其中传递Sector实体。考虑按扇区ID检查:

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