Implementing the same functionality as a simple Contains() query becomes more complex when using Entity Framework and composite primary keys. This article discusses various ways to solve this problem:
Attempting to use a tuple representing a composite primary key value for a direct join or a Contains operation fails in the Entity Framework. This is because such operations cannot be converted to SQL, because tuples are not considered as original values in this context.
Another way is to use AsEnumerable() to extract the database table data into memory and perform the necessary filtering using LINQ to Objects. However, for large tables, this solution is extremely inefficient.
Using a separate Contains() statement for each composite primary key component will result in incorrect filtering. This approach can produce misleading results because entities containing only one matching component will be mistakenly included.
You can use a modified Contains() query containing the calculated values derived from the composite primary key component (for example, entity.Id1 * entity.Id2). However, this solution is non-searchable and leads to poor performance.
The most scalable method is to combine Contains and memory connections. This method uses a preliminary Contains() query to narrow down the result set and then refine it more precisely via memory connections.
Preliminary builders like Linqkit allow the creation of queries containing OR clauses for each composite primary key value combination. While this method may work for small lists, for large lists, its performance will be degraded.
Another way is to use UNION to combine multiple queries that combine each composite primary key value. This solution may work for small to medium-sized lists.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3