Home > Backend Development > C++ > How to Use the Contains() Function in Linq to Entities?

How to Use the Contains() Function in Linq to Entities?

Susan Sarandon
Release: 2024-10-29 11:14:29
Original
559 people have browsed it

How to Use the Contains() Function in Linq to Entities?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template