0

I have this LINQ:

    private static object getObjectModels(DbContext context, IQueryable<int> contractsID)
    {
        return (from objectModel in context.Set<ObjectModel>()
                where "column named conId contains contractsID "
                select new ContractHelper
                {
                    Id = contract.Id,
                    ClientId = contract.ClientId,
                });
    }

I need to select from table records where column named conID have values of contractsID.

The contractsID is int array. The conID is int value column.

What have I write in this row: where "column named conId contains contractsID" to get all records where column conID have item that equal to item in contractsID array?

Wesley Lomax
  • 2,067
  • 2
  • 20
  • 34
Michael
  • 13,950
  • 57
  • 145
  • 288
  • 2
    You need to replicate an `IN` clause: [http://stackoverflow.com/questions/959752/where-in-clause-in-linq](http://stackoverflow.com/questions/959752/where-in-clause-in-linq) – markpsmith Oct 06 '15 at 13:01

2 Answers2

4

You might be able to invert the where clause and use a 'contains', such as:

private static object getObjectModels(DbContext context, IQueryable<int> contractsID)
    {
        return (from objectModel in context.Set<ObjectModel>()
                where objectModel.conId.HasValue && contractsID.Contains(objectModel.conId)
                select new ContractHelper
                {
                    Id = contract.Id,
                    ClientId = contract.ClientId,
                });
    }

You might need to convert the IQueryable to a list however.

var myIds = contractIDs.ToList();
...
where myIds.Contains(objectModel.conId)
...
Russ Clarke
  • 17,511
  • 4
  • 41
  • 45
2

You can go with an int array to make linq translate to the correct IN SQL syntax

  private static object getObjectModels(DbContext context, IQueryable<int> contractsID)
    {
         // Necessary to translate Contains to SQL IN  CLAUSE
        int [] contractIdsArray = contractsID.ToArray() ; 

        return (from objectModel in context.Set<ObjectModel>()
                where contractIdsArray.Contains(objectModel.conId)
                select new ContractHelper
                {
                    Id = contract.Id,
                    ClientId = contract.ClientId,
                });
    }
Perfect28
  • 11,089
  • 3
  • 25
  • 45