2

I'm using Entity Framework 4.1 on a SQLCE 4 database and my context is a DbContext.

The purpose of the following code is to search for a list of entries where the "ProtocolName" property is contained within a given list.

This version of the code that supplies the list of permitted values as a List works fine:

List<string> lstPossibles = new List<string>("Name1", "Name2");
query = from le in context.DaLogEvents where lstPossibles.Contains(le.ProtocolName) select le;

However, this version of the code that supplies the permitted values as an array throws an exception when the query.ToList() is invoked:

string[] aryPossibles = new string[] { "Name1", "Name2" };
query = from le in context.DaLogEvents where aryPossibles.Contains(le.ProtocolName) select le;

The reported exception is:

"LINQ to Entities does not recognize the method 'Boolean Contains[String](System.String[], System.String)' method, and this method cannot be translated into a store expression."

It took me a while to figure out to use List rather than string[] because I've seen a fair number of references on this site to the use of the array method.

Is this an issue with just EF 4.1?

Slauma
  • 175,098
  • 59
  • 401
  • 420

1 Answers1

0

Using an array "usually" works as well as using a list or any other IEnumerable<string> implementation - given that the extension method Contains is the standard LINQ extension method of IEnumerable<T>.

The exception you get ...

...the method 'Boolean Contains[String](System.String[], System.String)'...

... is surprising because it indicates that the compiler doesn't use the LINQ extension method. If it would use the LINQ method the exception would be something like:

...the method 'Boolean Contains[String](IEnumerable`1[String], System.String)'...

Or better: If it would use this method there wouldn't be an exception at all.

The question is: Do you have somewhere an extension method Contains for string[] - either handwritten or perhaps included from some other assembly/namespace? Something like:

public static class SomeExtensions
{
    public static bool Contains<T>(this T[] ary, T value)
    {
        // ...
    }
}

If this thing is used (your code would compile) you would indeed get the exception because LINQ to Entities does not know how to translate such a custom method into SQL (="store expression"), no matter how it is implemented.

Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Great call!! That was the problem. There was an extension method in a well used and aged "common/utility" class library that has the following signature: public static bool Contains (this T[] array, T val) – Lionel Johnson Nov 10 '11 at 22:11