简体   繁体   中英

linq query on list id's

I have a list of id's and I need to get all records correscponding to each id in the list .

below is the sample code

public List<Items> LoadLineItemByPkeys(IEnumerable<long> ItemId)
{
    var ItemList = CurrentSession.Query<LineItem>()
      .Where(l =>itemId.Contains(l.id))
      .ToList();
    return ItemList ;
}

but i am getting exception

An exception of type 'NHibernate.Exceptions.GenericADOException' occurred in NHibernate.dll but was not handled in user code

inner exception:-

Failed to convert parameter value from a WhereSelectArrayIterator`2 to a Int64. Please help me on this.

when i executed same query in LINQPad, i am getting the results.

You may be having trouble due to how you've passed in the IDs. You may find that converting that sequence into a list or an array would help:

// Various names to be more conventional/readable
public List<Items> LoadLineItemsById(IEnumerable<long> ids)
{
    var idList = ids.ToList();
    return CurrentSession.Query<LineItem>()
                         .Where(item => idList.Contains(item.Id))
                         .ToList();
}

If i'm not mistaking you cannot make use of the contains method.

You'll have to make use of .IsIn()

public List<Items> LoadLineItemByPkeys(IEnumerable<long> itemIds)
{
    var lineItemList = CurrentSession.QueryOver<LineItem>()
      .WhereRestrictionOn(l =>l.id).IsIn(itemIds).List()
      .ToList();
    return lineItemList ;
}

This wil generate a sql statement with an in operator. Be aware of the limitations of this operator. Some db's have a limit of 1000 arguments, other of 2000 etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM