Contains() Function Workaround Using Linq to Entities
Question:
How to use the Contains() function within Linq to Entities queries, despite its lack of support?
Answer:
Update: As of Entity Framework (EF) version 4 and later, Contains() is supported directly.
For earlier versions of EF, a workaround is necessary:
Custom Extension Method for Contains()
Create the following extension method:
<code class="csharp">public static IQueryable<TEntity> WhereIn<TEntity, TValue>( this ObjectQuery<TEntity> query, Expression<Func<TEntity, TValue>> selector, IEnumerable<TValue> collection) { // ... (implementation remains the same as in the provided code) }</code>
Optional Static Collection Version
Optionally, you can create a version that allows a static collection as input:
<code class="csharp">public static IQueryable<TEntity> WhereIn<TEntity, TValue>( this ObjectQuery<TEntity> query, Expression<Func<TEntity, TValue>> selector, params TValue[] collection) { return WhereIn(query, selector, (IEnumerable<TValue>)collection); }</code>
Usage:
With this extension method, you can use Contains() in your Linq to Entities queries as follows:
<code class="csharp">public static void Main() { using (MyObjectContext context = new MyObjectContext()) { // Using method 1 - collection provided as collection var contacts1 = context.Contacts.WhereIn(c => c.Name, GetContactNames()); // Using method 2 - collection provided statically var contacts2 = context.Contacts.WhereIn(c => c.Name, "Contact1", "Contact2", "Contact3", "Contact4"); } }</code>
The above is the detailed content of How to Use the Contains() Function in Linq to Entities?. For more information, please follow other related articles on the PHP Chinese website!