.NET Entity Framework - Using .Contains() to find a byte value in a Where expression

后端 未结 2 1176
迷失自我
迷失自我 2020-12-16 11:44

I am building an IQueryable based on parameters I get from the user. One of those parameters is a multi-select and I need to retrieve records that contain any of the selecte

相关标签:
2条回答
  • 2020-12-16 12:13

    I was able to reproduce your error in LINQPad, and found that using a List<byte> instead of a byte[] would work:

    // byte[] ids = new byte[] { 1, 64 };  <== causes ArgumentException
    List<byte> ids = new List<byte> { 1, 64};
    
    var c = Courses.Where (co => ids.Contains(co.CourseDeliveryId));
    

    will generate the following sql and return results:

    SELECT 
    [Extent1].[CourseId] AS [CourseId], 
    [Extent1].[CourseName] AS [CourseName], 
    [Extent1].[CourseDeliveryId] AS [CourseDeliveryId]
    FROM [dbo].[Courses] AS [Extent1]
    WHERE [Extent1].[CourseDeliveryId] IN (1,64)
    

    It's also interesting that using an int[] or short[] would also work, producing this sql:

    SELECT 
    [Extent1].[CourseId] AS [CourseId], 
    [Extent1].[CourseName] AS [CourseName], 
    [Extent1].[CourseDeliveryId] AS [CourseDeliveryId]
    FROM [dbo].[Courses] AS [Extent1]
    WHERE (1 =  CAST( [Extent1].[CourseDeliveryId] AS int)) OR (64 =  CAST( [Extent1].[CourseDeliveryId] AS int))
    

    but using a byte[] causes an exception. I can only guess that the SQL Server EF provider is trying to treat byte[] in some special way, resulting in this exception.

    0 讨论(0)
  • 2020-12-16 12:38

    Although using different containers solve the issue, you do not have to change the container type. All you need to do is assign it to IEnumerable:

    IEnumerable<byte> ids = parameters.DeliveryID.ToArray();
    courses = courses.Where(c => ids.Contains(c.CourseDeliveryID));
    

    (In this specific case you can just use ToList() instead of ToArray() but in the general case if you get the byte array and do not want to rebuild it as a list this will do)

    0 讨论(0)
提交回复
热议问题