2

I've read other questions about this but I can't seem to figure it..

I have a two tables and a linking table between them like so:

Organisations (OrganisationID, Name)
Sectors (SectorID, Name)
Organisations_Sectors (OrganisationID, SectorID)

Why does this fail:

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

(Hope it's not confusing with the arbitrary entity names. Sector != Section.)

The exception that is thrown is Unable to create a constant value of type 'H.Data.Sector'. Only primitive types or enumeration types are supported in this context.

notAnonymousAnymore
  • 2,637
  • 9
  • 49
  • 74
  • Possible duplicate of [Entity Framework - "Unable to create a constant value of type..." exception](http://stackoverflow.com/questions/7379394/entity-framework-unable-to-create-a-constant-value-of-type-exception) – Palindromer Mar 12 '17 at 17:22

1 Answers1

3

You should pass primitive type to Contains method, so you can't pass Sector entity there. Consider to check by sector id:

IQueryable<int> orgIds = db.Organisations
   .Where(o => o.Sectors.Any(s => s.SectorId == sectorId) && !o.IsInternational)
   .Select(o => o.OrganisationID);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459