简体   繁体   中英

Constructing dynamic queries with c# + Entity Framework + Stored procedure

I am working on a piece of functionality where a user may select multiple parameters with multiple values in each parameter. I am trying to figure out a way to design this functionality in my application using C#, entity framework with entities being mapped to stored procedure. Due to security reasons, my application has to access the database via a surrogate database which has only stored procedures. Therefore my entities are mapped to stored procedures for insert, update, and select. Ultimately, I need to pass the filters chosen by the user to the stored procedure for querying the database. One of the solutions I thought of is to retrieve all the data to my business layer and use linq to filter out further. But this is not ideal due to the amount of data being filtered in the memory rater than in the database which is more better suited to do this kind of complex query. I have seen posts for constructing dynamic queries with linq, but in these kind of posts, the entities are mapped to the tables which makes it easier. Any help here will be greatly appreciated. Thank You, sirkal

EF (and LINQ for that matter) use deferred execution. You can fairly easily create a dynamic query using IQueryable (Google search time?) and creating the filter criteria in an object you build (you can do it without the object, but think reusable).

As for the SQL sproc, you can also solve it there by passing in all of the items that can possibly change the filter and having SQL dynamically work on the data to produce a result set.

Which to choose? It really depends on where the core competency is in your group. I prefer C# code mostly due to familiarity (spent years doing sprocs, but dynamic sprocs can be a royal pain).

Now, one thing you do want to be wary of is ending up with dynamic queries that cannot easily be tuned by the server (like statistics in SQL Server, although other RDBMSes use similar concepts). One issue I have seen with LINQ to SQL, for example, is dynamic queries that cause SQL to perform less than optimally, requiring a lot of handholding from the DBA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM