I’m currently having issues with using LINQ to SQL for my project. This is because most of the lengthy SQL queries (or views, rather) are hard-coded into C#, and what we’ve been doing all along is to use context.Database.SqlQuery<ClassName>(sql, sqlParams).
It’s been generally very effective, but right now we need something more dynamic. We need to plug in stuff like .Where(x => x.Name.Contains("Anonymous")).Take(20) or something else along the lines. However, plugging in directly to the previously mentioned line of code would result in the following:
context.Database.SqlQuery<ClassName>(sql, sqlParams).Where(x => x.Name.Contains("Anonymous")).Take(20);
While it actually works and pulls the top 20 records where the name contains “Anonymous”, the performance is pretty bad. What it does behind the scenes is to take all the records from that table and then finally filtering them after having loaded them to memory.
I would then like to ask, is there any way to translate the text SQL to LINQ, or translate the LINQ to SQL, such that I can execute both my text SQL and LINQ in one single statement. If you don’t actually have a solution, I’d gladly appreciate suggestions too…!
EDIT: I’ve considered using Expression Trees, but I’m not sure how they can actually fit into the picture. Also, I’ve considered using database views. But there are so many views (quite a number per table) it would definitely be a hassle to port everything over to MS SQL and then rewriting all the querying logic.
You can’t really do that as expression trees generate SQL from an expression that’s built dynamically i.e. from the expressions you can “compile” a SQL, what you’re asking is akin to asking for a “SQL-to-LINQ dissasembler”.
My suggestion for your problem is – take your SQL queries and save them as views in the database, then map your views in the LINQ-To-SQL .dbml files and add your LINQ queries on top of that.
This way LINQ will query from your view, and return only the data you need.
(you can also use table-valued functions instead of views)