【问题标题】:Entity Framework - Unable to create a constant value of type实体框架 - 无法创建类型的常量值
【发布时间】:2014-01-02 05:23:27
【问题描述】:

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

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

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

(希望它不会与任意实体名称混淆。Sector != Section。)

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

【问题讨论】:

标签: c# linq entity-framework


【解决方案1】:

您应该将原始类型传递给Contains 方法,因此您不能在那里传递Sector 实体。考虑按扇区 id 检查:

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

【讨论】:

  • 完美运行。感谢您的超快速响应:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多