<p>I took a look at the "Beginner's Guide to LINQ" post here on StackOverflow (<a href="https://stackoverflow.com/questions/8050/beginners-guide-to-linq">Beginners Guide to LINQ</a>), but had a follow-up question:</p>

<p>We're about to ramp up a new project where nearly all of our database op's will be fairly simple data retrievals (there's another segment of the project which already writes the data). Most of our other projects up to this point make use of stored procedures for such things. However, I'd like to leverage LINQ-to-SQL if it makes more sense.</p>

<p>So, the question is this: For simple data retrievals, which approach is better, LINQ-to-SQL or stored procs? Any specific pro's or con's?</p>

<p>Thanks.</p>

[{'answer_id': 14531, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 6, 'selected': False, 'text': "<p>Linq to Sql.</p>\n\n<p>Sql server will cache the query plans, so there's no performance gain for sprocs.</p>\n\n<p>Your linq statements, on the other hand, will be logically part of and tested with your application.  Sprocs are always a bit separated and are harder to maintain and test.</p>\n\n<p>If I was working on a new application from scratch right now I would just use Linq, no sprocs.</p>\n"}, {'answer_id': 14533, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 2, 'selected': False, 'text': "<p>I'm assuming you mean Linq To Sql</p>\n\n<p>For any CRUD command it's easy to profile the performance of a stored procedure vs. any technology. In this case any difference between the two will be negligible. Try profiling for a 5 (simple types) field object over 100,000 select queries to find out if there's a real difference.</p>\n\n<p>On the other hand the real deal-breaker will be the question on whether you feel comfortable putting your business logic on your database or not, which is an argument against stored procedures.</p>\n"}, {'answer_id': 14537, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 4, 'selected': False, 'text': "<p>The best code is no code, and with stored procedures you have to write at least some code in the database and code in the application to call it , whereas with LINQ to SQL or LINQ to Entities, you don't have to write any additional code beyond any other LINQ query aside from instantiating a context object. </p>\n"}, {'answer_id': 14549, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 6, 'selected': False, 'text': '<p>I am generally a proponent of putting everything in stored procedures, for all of the reasons DBAs have been harping on for years.  In the case of Linq, it is true that there will be no performance difference with simple CRUD queries.</p>\n\n<p>But keep a few things in mind when making this decision: using any ORM couples you tightly to your data model.  A DBA has no freedom to make changes to the data model without forcing you to change your compiled code.  With stored procedures, you can hide these sorts of changes to an extent, since the parameter list and results set(s) returned from a procedure represent its contract, and the innards can be changed around, just so long as that contract is still met.</p>\n\n<p>And also, if Linq is used for more complex queries, tuning the database becomes a much more difficult task.  When a stored procedure is running slow, the DBA can totally focus on the code in isolation, and has lots of options, just so that contract is still satisfied when he/she is done.</p>\n\n<p>I have seen many, many cases where serious problems in an application were addressed by changes to the schema and code in stored procedures without any change to deployed, compiled code.</p>\n\n<p>Perhaps a hybird approach would be nice with Linq?  Linq can, of course, be used to call stored procedures.</p>\n'}, {'answer_id': 14556, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 5, 'selected': False, 'text': "<p>For basic data retrieval I would be going for Linq without hesitation.</p>\n\n<p>Since moving to Linq I've found the following advantages:</p>\n\n<ol>\n<li>Debugging my DAL has never been easier.</li>\n<li>Compile time safety when your schema changes is priceless.</li>\n<li>Deployment is easier because everything is compiled into DLL's. No more managing deployment scripts.</li>\n<li>Because Linq can support querying anything that implements the IQueryable interface, you will be able to use the same syntax to query XML, Objects and any other datasource without having to learn a new syntax</li>\n</ol>\n"}, {'answer_id': 16268, 'author': 'lomaxx', 'author_id': 493, 'author_profile': 'https://Stackoverflow.com/users/493', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>A DBA has no freedom to make changes\n  to the data model without forcing you\n  to change your compiled code. With\n  stored procedures, you can hide these\n  sorts of changes to an extent, since\n  the parameter list and results set(s)\n  returned from a procedure represent\n  its contract, and the innards can be\n  changed around, just so long as that\n  contract is still met.</p>\n</blockquote>\n\n<p>I really don't see this as being a benefit. Being able to change something in isolation might sound good in theory, but just because the changes fulfil a contract doesn't mean it's returning the correct results. To be able to determine what the correct results are you need context and you get that context from the calling code.</p>\n"}, {'answer_id': 28992, 'author': 'Chris Gillum', 'author_id': 2069, 'author_profile': 'https://Stackoverflow.com/users/2069', 'pm_score': 9, 'selected': True, 'text': '<p>Some advantages of LINQ over sprocs:</p>\n\n<ol>\n<li><strong>Type safety</strong>: I think we all understand this.</li>\n<li><strong>Abstraction</strong>: This is especially true with <a href="http://msdn.microsoft.com/en-us/library/bb386964.aspx" rel="noreferrer">LINQ-to-Entities</a>.  This abstraction also allows the framework to add additional improvements that you can easily take advantage of.  <a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx" rel="noreferrer">PLINQ</a> is an example of adding multi-threading support to LINQ.  Code changes are minimal to add this support.  It would be MUCH harder to do this data access code that simply calls sprocs.</li>\n<li><strong>Debugging support</strong>: I can use any .NET debugger to debug the queries.  With sprocs, you cannot easily debug the SQL and that experience is largely tied to your database vendor (MS SQL Server provides a query analyzer, but often that isn\'t enough).</li>\n<li><strong>Vendor agnostic</strong>: LINQ works with lots of databases and the number of supported databases will only increase.  Sprocs are not always portable between databases, either because of varying syntax or feature support (if the database supports sprocs at all).</li>\n<li><strong>Deployment</strong>: Others have mentioned this already, but it\'s easier to deploy a single assembly than to deploy a set of sprocs.  This also ties in with #4.</li>\n<li><strong>Easier</strong>: You don\'t have to learn T-SQL to do data access, nor do you have to learn the data access API (e.g. ADO.NET) necessary for calling the sprocs.  This is related to #3 and #4.</li>\n</ol>\n\n<p>Some disadvantages of LINQ vs sprocs:</p>\n\n<ol>\n<li><strong>Network traffic</strong>: sprocs need only serialize sproc-name and argument data over the wire while LINQ sends the entire query.  This can get really bad if the queries are very complex.  However, LINQ\'s abstraction allows Microsoft to improve this over time.</li>\n<li><strong>Less flexible</strong>: Sprocs can take full advantage of a database\'s featureset.  LINQ tends to be more generic in it\'s support.  This is common in any kind of language abstraction (e.g. C# vs assembler).</li>\n<li><strong>Recompiling</strong>: If you need to make changes to the way you do data access, you need to recompile, version, and redeploy your assembly.  Sprocs can <em>sometimes</em> allow a DBA to tune the data access routine without a need to redeploy anything.</li>\n</ol>\n\n<p>Security and manageability are something that people argue about too.</p>\n\n<ol>\n<li><strong>Security</strong>: For example, you can protect your sensitive data by restricting access to the tables directly, and put ACLs on the sprocs.  With LINQ, however, you can still restrict direct access  to tables and instead put ACLs on updatable table <em>views</em> to achieve a similar end (assuming your database supports updatable views).  </li>\n<li><strong>Manageability</strong>: Using views also gives you the advantage of shielding your application non-breaking from schema changes (like table normalization).  You can update the view without requiring your data access code to change.</li>\n</ol>\n\n<p>I used to be a big sproc guy, but I\'m starting to lean towards LINQ as a better alternative in general.  If there are some areas where sprocs are clearly better, then I\'ll probably still write a sproc but access it using LINQ. :)</p>\n'}, {'answer_id': 32101, 'author': 'kenny', 'author_id': 3225, 'author_profile': 'https://Stackoverflow.com/users/3225', 'pm_score': 3, 'selected': False, 'text': '<p>LINQ doesn\'t prohibit the use of stored procedures. I\'ve used mixed mode with LINQ-SQL and <a href="http://codebetter.com/blogs/david.hayden/archive/2008/02/19/linq-to-sql-and-stored-procedures-visual-studio-2008-and-repository-factory.aspx" rel="noreferrer">LINQ-storedproc</a>. Personally, I\'m glad I don\'t have to write the stored procs....pwet-tu.</p>\n'}, {'answer_id': 32688, 'author': 'SQLMenace', 'author_id': 740, 'author_profile': 'https://Stackoverflow.com/users/740', 'pm_score': 5, 'selected': False, 'text': '<p>LINQ will bloat the procedure cache</p>\n\n<p>If an application is using LINQ to SQL and the queries involve the use of strings that can be highly variable in length, the SQL Server procedure cache will become bloated with one version of the query for every possible string length. For example, consider the following very simple queries created against the Person.AddressTypes table in the AdventureWorks2008 database:</p>\n\n<pre><code>var p = \n    from n in x.AddressTypes \n    where n.Name == "Billing" \n    select n;\n\nvar p = \n    from n in x.AddressTypes \n    where n.Name == "Main Office" \n    select n;\n</code></pre>\n\n<p>If both of these queries are run, we will see two entries in the SQL Server procedure cache: One bound with an NVARCHAR(7), and the other with an NVARCHAR(11). Now imagine if there were hundreds or thousands of different input strings, all with different lengths. The procedure cache would become unnecessarily filled with all sorts of different plans for the exact same query. </p>\n\n<p>More here: <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=363290&amp;wa=wsignin1.0" rel="noreferrer">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=363290</a></p>\n'}, {'answer_id': 58309, 'author': 'Dr8k', 'author_id': 6014, 'author_profile': 'https://Stackoverflow.com/users/6014', 'pm_score': 4, 'selected': False, 'text': "<p>I think the pro LINQ argument seems to be coming from people who don't have a history with database development (in general).</p>\n\n<p>Especially if using a product like VS DB Pro or Team Suite, many of the arguments made here do not apply, for instance:</p>\n\n<p>Harder to maintain and Test:\nVS provides full syntax checking, style checking, referential and constraint checking and more. It also provide full unit testing capabilities and refactoring tools.</p>\n\n<p>LINQ makes true unit testing impossible as (in my mind) it fails the ACID test.</p>\n\n<p>Debugging is easier in LINQ:\nWhy? VS allows full step-in from managed code and regular debugging of SPs.</p>\n\n<p>Compiled into a single DLL rather than deployment scripts:\nOnce again, VS comes to the rescue where it can build and deploy full databases or make data-safe incremental changes.</p>\n\n<p>Don't have to learn TSQL with LINQ:\nNo you don't, but you have to learn LINQ - where's the benefit?</p>\n\n<blockquote>\n  <p>I really don't see this as being a benefit. Being able to change something in isolation might sound good in theory, but just because the changes fulfil a contract doesn't mean it's returning the correct results. To be able to determine what the correct results are you need context and you get that context from the calling code.</p>\n</blockquote>\n\n<p>Um, loosely coupled apps are the ultimate goal of all good programmers as they really do increase flexibility. Being able to change things in isolation is fantastic, and it is your unit tests that will ensure it is still returning appropriate results.</p>\n\n<p>Before you all get upset, I think LINQ has its place and has a grand future. But for complex, data-intensive applications I do not think it is ready to take the place of stored procedures. This was a view I had echoed by an MVP at TechEd this year (they will remain nameless).</p>\n\n<p>EDIT: The LINQ to SQL Stored Procedure side of things is something I still need to read more on - depending on what I find I may alter my above diatribe ;)</p>\n"}, {'answer_id': 187578, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>LINQ definitely has its place in application-specific databases and in small businesses.</p>\n\n<p>But in a large enterprise, where central databases serve as a hub of common data for many applications, we need abstraction. We need to centrally manage security and show access histories. We need to be able to do impact analysis: if I make a small change to the data model to serve a new business need, what queries need to be changed and what applications need to be re-tested? Views and Stored Procedures give me that. If LINQ can do all that, and make our programmers more productive, I'll welcome it -- does anyone have experience using it in this kind of environment?</p>\n"}, {'answer_id': 217429, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Also, there is the issue of possible 2.0 rollback. Trust me it has happened to me a couple of times so I am sure it has happened to others.</p>\n\n<p>I also agree that abstraction is the best. Along with the fact, the original purpose of an ORM is to make RDBMS match up nicely to the OO concepts. However, if everything worked fine before LINQ by having to deviate a bit from OO concepts then screw 'em. Concepts and reality don't always fit well together. There is no room for militant zealots in IT.</p>\n"}, {'answer_id': 336310, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>LINQ is new and has its place. LINQ is not invented to replace stored procedure. </p>\n\n<p>Here I will focus on some performance myths &amp; CONS, just for "LINQ to SQL", of course I might be totally wrong ;-)</p>\n\n<p>(1)People say LINQ statment can "cache" in SQL server, so it doesn\'t lose performance. Partially true. "LINQ to SQL" actually is the runtime translating LINQ syntax to TSQL statment. So from the performance perspective,a hard coded ADO.NET SQL statement has no difference than LINQ. </p>\n\n<p>(2)Given an example, a customer service UI has a "account transfer" function. this function itself might update 10 DB tables and return some messages in one shot. With LINQ, you have to build a set of statements and send them as one batch to SQL server. the performance of this translated LINQ->TSQL batch can hardly match stored procedure. Reason? because you can tweak the smallest unit of the statement in Stored procedue by using the built-in SQL profiler and execution plan tool, you can not do this in LINQ.</p>\n\n<p>The point is, when talking single DB table and small set of data CRUD, LINQ is as fast as SP. But for much more complicated logic, stored procedure is more performance tweakable.</p>\n\n<p>(3)"LINQ to SQL" easily makes newbies to introduce performance hogs. Any senior TSQL guy can tell you when not to use CURSOR (Basically you should not use CURSOR in TSQL in most cases). With LINQ and the charming "foreach" loop with query, It\'s so easy for a newbie to write such code:</p>\n\n<pre><code>foreach(Customer c in query)\n{\n  c.Country = "Wonder Land";\n}\nctx.SubmitChanges();\n</code></pre>\n\n<p>You can see this easy decent code is so attractive. But under the hood, .NET runtime just translate this to an update batch. If there are only 500 lines, this is 500 line TSQL batch; If there are million lines, this is a hit. Of course, experienced user won\'t use this way to do this job, but the point is, it\'s so easy to fall in this way.</p>\n'}, {'answer_id': 1065406, 'author': 'Craig', 'author_id': 131272, 'author_profile': 'https://Stackoverflow.com/users/131272', 'pm_score': 3, 'selected': False, 'text': "<p>IMHO, RAD = LINQ, RUP = Stored Procs.  I worked for a large Fortune 500 company for many years, at many levels including management, and frankly, I would never hire RUP developers to do RAD development.  They are so siloed that they very limited knowledge of what to do at other levels of the process.  With a siloed environment, it makes sense to give DBAs control over the data through very specific entry points, because others frankly don't know the best ways to accomplish data management.</p>\n\n<p>But large enterprises move <em>painfully</em> slow in the development arena, and this is extremely costly. There are times when you need to move faster to save both time and money, and LINQ provides that and more in spades.</p>\n\n<p>Sometimes I think that DBAs are biased against LINQ because they feel it threatens their job security.  But that's the nature of the beast, ladies and gentlemen.</p>\n"}, {'answer_id': 6262185, 'author': 'Kyaw Thura', 'author_id': 683542, 'author_profile': 'https://Stackoverflow.com/users/683542', 'pm_score': 2, 'selected': False, 'text': '<p>According to gurus, I define LINQ as motorcycle and SP as car.\nIf you want to go for a short trip and only have small passengers(in this case 2), go gracefully with LINQ.\nBut if you want to go for a journey and have large band, i think you should choose SP.</p>\n\n<p>As a conclusion, choosing between motorcycle or car is depend on your route (business), length (time), and passengers (data).</p>\n\n<p>Hope it helps, I may be wrong. :D</p>\n'}, {'answer_id': 7042536, 'author': 'live-love', 'author_id': 436341, 'author_profile': 'https://Stackoverflow.com/users/436341', 'pm_score': 0, 'selected': False, 'text': '<p>Both LINQ and SQL have their places. Both have their disadvantages and advantages.</p>\n\n<p>Sometimes for complex data retrieval you might need stored procs. And sometimes you may want other people to use your stored proc in Sql Server Management Studio.</p>\n\n<p>Linq to Entities is great for fast CRUD development.</p>\n\n<p>Sure you can build an app using only one or the other. Or you can mix it up. It all comes down to your requirements. But SQL stored procs will no go away any time soon.</p>\n'}, {'answer_id': 7170450, 'author': 'pokrate', 'author_id': 140939, 'author_profile': 'https://Stackoverflow.com/users/140939', 'pm_score': 1, 'selected': False, 'text': '<p>The outcome can be summarized as </p>\n\n<p>LinqToSql for small sites, and prototypes. It really saves time for Prototyping.</p>\n\n<p>Sps : Universal. I can fine tune my queries and always check ActualExecutionPlan / EstimatedExecutionPlan.</p>\n'}, {'answer_id': 7839840, 'author': 'totaldonet', 'author_id': 1005740, 'author_profile': 'https://Stackoverflow.com/users/1005740', 'pm_score': 1, 'selected': False, 'text': '<pre><code>Create PROCEDURE userInfoProcedure\n    -- Add the parameters for the stored procedure here\n    @FirstName varchar,\n    @LastName varchar\nAS\nBEGIN\n\n    SET NOCOUNT ON;\n\n    -- Insert statements for procedure here\n    SELECT FirstName  , LastName,Age from UserInfo where FirstName=@FirstName\n    and LastName=@FirstName\nEND\nGO\n</code></pre>\n\n<p><a href="http://www.totaldotnet.com/Article/ShowArticle121_StoreProcBasic.aspx" rel="nofollow">http://www.totaldotnet.com/Article/ShowArticle121_StoreProcBasic.aspx</a></p>\n'}, {'answer_id': 9197542, 'author': 'Todd Bandrowsky', 'author_id': 1197706, 'author_profile': 'https://Stackoverflow.com/users/1197706', 'pm_score': 3, 'selected': False, 'text': "<p>I think you need to go with procs for anything real.</p>\n\n<p>A) Writing all your logic in linq means your database is less useful because only your application can consume it.</p>\n\n<p>B) I'm not convinced that object modelling is better than relational modelling anyway.</p>\n\n<p>C) Testing and developing a stored procedure in SQL is a hell of a lot faster than a compile edit cycle in any Visual Studio environment.  You just edit, F5 and hit select and you are off to the races.</p>\n\n<p>D) It's easier to manage and deploy stored procedures than assemblies.. you just put the file on the server, and press F5...</p>\n\n<p>E) Linq to sql still writes crappy code at times when you don't expect it.</p>\n\n<p>Honestly, I think the ultimate thing would be for MS to augment t-sql so that it can do a join projection impliclitly the way linq does.  t-sql should know if you wanted to do order.lineitems.part, for example.</p>\n"}, {'answer_id': 9588019, 'author': 'dansasu11', 'author_id': 900746, 'author_profile': 'https://Stackoverflow.com/users/900746', 'pm_score': 1, 'selected': False, 'text': "<p>Stored procedure makes testing easier and you can change the query without touching the application code. Also with linq, getting a data does not mean its the right data. And testing the correctness of the data means running the application but with stored procedure it's easy to test without touching the application.</p>\n"}, {'answer_id': 9645613, 'author': 'Neo', 'author_id': 1260812, 'author_profile': 'https://Stackoverflow.com/users/1260812', 'pm_score': 2, 'selected': False, 'text': '<p>For simple CRUD operations with a single data access point, I would say go for LINQ if you feel comfortable with the syntax. For more complicated logic I think sprocs are more efficiant performance-wise if you are good at T-SQL and its more advanced operations. You also have the help from Tuning Advisor, SQL Server Profiler, debugging your queries from SSMS etc. </p>\n'}, {'answer_id': 12591415, 'author': 'Manish', 'author_id': 1698615, 'author_profile': 'https://Stackoverflow.com/users/1698615', 'pm_score': 2, 'selected': False, 'text': '<p>All these answers leaning towards LINQ are mainly talking about EASE of DEVELOPMENT which is more or less connected to poor quality of coding or laziness in coding. I am like that only. </p>\n\n<p>Some advantages or Linq, I read here as , easy to test, easy to debug etc, but these are no where connected to Final output or end user. This is always going cause the trouble the end user on performance. Whats the point loading many things in memory and then applying filters on in using LINQ? </p>\n\n<p>Again TypeSafety, is caution that "we are careful to avoid wrong typecasting" which again poor quality we are trying to improve by using linq. Even in that case, if anything in database changes, e.g. size of String column, then linq needs to be re-compiled and would not be typesafe without that .. I tried.</p>\n\n<p>Although, we found is good, sweet, interesting etc while working with LINQ, it has shear disadvantage of making developer lazy :) and it is proved 1000 times that it is bad (may be worst) on performance compared to Stored Procs.</p>\n\n<p>Stop being lazy. I am trying hard. :)</p>\n'}]
['https://Stackoverflow.com/questions/14530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1683/']