Stored procedure vs Scaffolding [closed] - asp.net

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I m using ASP.NET Core 1.0 and website will be big (expecting about 5,000 visitors per hour). I have read many times that stored procedures are very fast and safe (in terms of SQL injection etc). But the code first EF if so easy that I want to use it, but the CRUD methods are hidden.
What will be the disadvantages (if any) to use Scaffolding with EF over SP's in terms of performance and security?

As long as you are using parameterized SQL you should be okay in terms of SQL injection. Never use user input to directly "build" SQL queries via string concatenation. So, as long as you use Entity Framework, stored procedures, or other tools correctly you shouldn't have to worry about SQL injection.
In terms of performance Entity Framework and other similar tools do perform worse overall. I'm not sure that alone is enough to keep you from using it though unless your program expects to have very heavy usage.
Stack Exchange has a nice open source tool Dapper is more lightweight than Entity but still has some nice features. It allows you to write raw SQL. See the section on performance in the Dapper readme. It performs very well, much better than other frameworks.
Staying away from stored procedures can help improve your architecture. Stored procedures may encourage you to encode lots of business logic in the database where unit and integration testing is more difficult to do. Also, deploying new apps becomes more difficult due to having to keep your application, stored procedures, and schema in sync.
So, in short Entity Framework is a great tool but can decrease performance. There are alternatives to stored procedures that are still high performing. Security shouldn't be an issue with whatever mature tool you use (correctly).
Edit to answer additional questions
Isn't Dapper susceptible to SQL injection?
Sure, but just about any tool is if used incorrectly. Here is the proper way to use Dapper example from their documentation. This query is parameterized.
connection.Execute(#"insert MyTable(colA, colB) values (#a, #b)",
new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
)
Now, here is a bad example that is susceptible to SQL injection:
connection.Execute(#"insert MyTable(colA, colB) values ('" + a + "', '" + b + "')")
Is Entity Framework always safe?
No, if you concatenate variables like the previous section and use ExecuteQuery you run into issues as well.
Are stored procedures always safe?
No, you can still run into SQL injection issues if you use dynamic SQL without parameterization.
Here is a link that discusses how ORMs and stored procedures are susceptible to SQL injection: http://www.troyhunt.com/2012/12/stored-procedures-and-orms-wont-save.html
What will be the disadvantages (if any) to use Scaffolding with EF over SP's in terms of performance and security?
No security issues if used properly like discussed above. Scaffolding is great if you're doing CRUD pages.
If you need to do advanced reporting you may need custom SQL which can still be done with Entity Framework. There is nothing wrong with using scaffolding for as much of your app as it makes sense to use it for and then use parameterized SQL via Entity for everything else. You can always even use scaffolding and then modify the generated classes to do what you want. For CRUD pages use scaffolding and for advanced queries write your own.
The performance hit from using Entity Framework for simple queries probably won't hurt you for basic queries - it should be minimal. You need to worry more about proper indexing and database schema most likely. A bad schema or incorrect indexing will cause performance issues in a hurry.

I like to think of choice between writing stored procedures and writing queries in EF as similar (in some way) to difference between programming in assembler and writing programs that are being runned in managed environment (like .NET and Java). Applications written for managed environments are always slower than those written in assembly language, but on the other hand it is usually much easier (and thus cheaper) to write complex applications using managed languages. With use of EF linq you will write your queries much faster and they will be usually simpler than their sql equivalents and thus easier to maintain. Other important factor is that applications changes rapidly, new functionalities are being added, old are being rewritten and along with this process tables and other db structures changes. When this happen your SP can no longer work correctly. When do you know that they should be fixed? Only when you run them. When do you know that you need to fix EF query because table changes? During compilation. And performance lost? Generally nowadays we have fast and quite cheap machines so we do not care that much. I examined once execution time of EF query and its sql equivalent - plain sql gained me decrease in execution time like 5% - this is nothing for me. And as sql queries are much more complex there is high probability of writing your query in wrong way so that it will be unnecessary slower. And finally, if you need in your app really great performance for some complex query - write it as SP and execute it easily with EF.
When it comes to security EF query generators always use sql parameters so they are as safe to sql injections as SP.

You can use scaffolding to create DB and views and replace the calls to inbuilt methods by your own methods.

Related

Entity Framework vs Stored Procedures

I am only starting with Entity Framework and I appreciate the direct mapping of code to the tables in my database. What I do not see just yet is the practicality of having to use EF over stored procedures and I would appreciate anyone's opinion about this. I am not being lazy and I am searching this myself at the moment. Thought I can post the question and hear from others as well.
My case is EF being an ORM is most suited to mapping in the tables in my database. But in a live web server many requests can happen at one time that may be taxing the database in having to compile the text queries prior to executing them compared to just simply executing stored procedure which are pre-compiled already. EF can also map to SPs but I feel that this is somewhat diminishing the value of ORM.
I would really appreciate an eye-opener in this case.
You might find Jeff's commentary on the subject helpful: http://www.codinghorror.com/blog/2005/05/stored-procedures-vs-ad-hoc-sql.html.
His point is basically that stored procedure's can be seen as a kind of premature optimization, and you really should make sure this is the performance bottleneck in your application before going that route. For instance, there are frameworks available to mock up 1000's of simultaneous web requests to see how your database will really perform under load in one situation versus the other.
Just because EF isn't using sprocs, it doesn't mean that the parameterised queries it runs won't get compiled and cached. SQL Server has got a lot more clever about that over the years.
One possible approach:
- dynamic sql for single objects
- SPs for parameterized lists and orders
The value of the ORM is usually its simplicity in creating the object model. One approach is described here: http://www.codeproject.com/Articles/362034/Populating-a-business-logical-layer-from-stored-pr

Entity Framework 4.0 Scaling and Security

I want to use an ORM, and have been looking at EF 4. Is this platform scalable. I see a lot of stuff on the web, but everything looks very biased in one way or the other. Anyone know of benchmarks or non-subjective information.
On that point, does EF prevent SQL injection or XSS. I know that it used parametrized queries, but is that enough?
Any help is appreciated.
Okay so i see two questions here.
Is EF Scalable
Very difficult (and subjective) to answer, but IMO yes.
Here's a few reasons why:
Utilizes a common querying language (LINQ)
Allows for multiple providers (SqlServer, Oracle, etc)
Allows bi-directional mapping (code first, model first, database first)
Includes "classic ADO.NET" support (stored procedures, Entity-SQL)
The main real benefit in scalability is how the framework is built on LINQ-to-Entities. When you write queries, you are not writing against SQL Server or Oracle, you are writing against the Model. Depending on what Provider you have setup (in web.config), EF will translate these model queries into the appropriate T-SQL (or P-SQL).
Therefore (theoretically), you could write code against SQL Server, then change the web.config provider to Oracle, and your code should work. Obviously this isn't the case for Entity-SQL though (as you are writing T-SQL, not LINQ).
Does EF prevent SQL injection or XSS
No ORM tool can really "prevent" SQL Injection attacks - they can only provide the developer with the tools to prevent it.
As with classic ADO.NET where you use parameterized queries, Entity Framework has Entity-SQL, which allows to to execute pre-generated SQL, stored procedures, etc.
In this scenario, you need to use parameterized queries to prevent SQL injection. For most EF work, you will be writing queries with LINQ, which is a lot safer because it gets hydrated through a lot of stages before it becomes SQL.
XSS is exploited on the client-side via things like injected JavaScript, dodgy emails, etc. Has nothing to do with Entity Framework. Prevention of XSS is done on the client-side with things like HTML encoding.
No. ORMs are not a panacea for scalability. There is such a things called the impedance mismatch of objects and databases which has been around for many years. ORMS try to solve this by providing magic code generation/mapping solutions that give the appearance of just working with objects.
In a multi-tier environment with many client programs and a single/many server scenario, for every change that has to be committed to the database, checks need to be performed to make sure that your not over writing someone elses change on the data, or trying to update data that has been removed. This is not a new problem introduced by ORMs but one which appears many many times throughout the ages of updating databases in N-Tier environments. ORMS do not solve this problem. In some cases, if the ORM is the single entry to the Database, the ORM becomes a bottle neck. This means that to create a scalable architecture using an ORM becomes problematic as having DB checks performed on the ORM means that the update anomaly checks could be by passed if your using an N-Tier ORM solution where you have duplicate ORM tiers.
For the reasons above, this is why we use stored procedures. But if your using stored procedures, which naturally obfuscate the underlying data structures of the database then this increases the impedance mismatch of objects and database entities. One thing about using stored procedures and relying on table locking/row rocking, some of the update scenarios are solved, as we shift the bottle neck to the performance of the underlying database design.
So whats the answer. Don't use objects for databases. Object are great for analysis, bad for code design when interacting with RDBMS databases.
If your really thinking SQL and RDBMS data solutions are a problem, which in some scenarios they are, take a look at some of the NOSQL solutions out there. Still not a panacea for all problems, but in some cases they provide a better solution than a straight SQL solution.
Objects are not the answer to all problems. Step back from your code, take a look at what your trying to do, and think if an object is the right approach.
As for security, no ORMS do not aid security. Although they do help prevent some forms of injection attacks.

Linq vs Stored Procedure

Which one is preferable for Enterprise CMS development:
LINQ or SP?
Generally what I do is LINQ to Views and LINQ to Stored Procedures. It's not a question of what is preferred because LINQ solves how to manage the data once it's queried where Stored Procedures are run on the SQL side to allow for query manipulation (or for me, mostly saving) of data which takes away from having the code to do it which is slower.
I would say you would want to use both if necessary. Are you saving to Entities that require multiple tables saves as one Entity? If so, use Stored Procedures with LINQ. If you're using 1 to 1 Entity relations to your tables then just use LINQ.
Stored Procedures can be used with Linq2Sql (and Entity Framework), so it isn't a choice of one or another.
I would cache the results from the database for a CMS as you likely to get the same data requested over and over again (cache the dataset, or use page caching, or cache the objects if using LINQ).
Then it doesn't matter if you use LINQ or an SP, but I would just use LINQ.
For simple CRUD table(no joins !!!) operations LINQ to SQL is fine, however for anything more complex (needing joins) I always use stored procedures (you can use Linq to stored procedures if you wish)
There are numerous debates around this on this site and others. For me, you can normally split the pro Linq camp into guys who have recently come into programming and have not had the history of having to use Stored procedures, ie not been heavily involved in the database side of previous projects.
Form my experience of working on several projects using pure LINQ, stored procedures and a mixture of both these are the two reasons I would stick to Linq for basic CRUD and stored procedures for anything more complex or relying on performance.
1 - Deploymenty/Security - Anyone that has worked in the real world a knows full well that having the database logic separated into stored procedures and not incorporated into the source code and released DLL is a massive advantage. You can add a proper security/access layer around each query using roles and SQL server security, imperative for any serious enterprise level company, and you can also make changes to the SQL of any stored procedure without having to do a new release of the main application (dll). I dont care how good you claim to be we have all had to fix live issues and performance bottlenecks using stored procedures and having to do this with a new application release would have been a nightmare.
2 - Performance/Code Smells - I have seen so many applications littered with huge amount of of badly written and inefficient Linq. Developers get lazy with Linq, little hidden lazy Linq to SQL queries which cause you a nightmare trying to debug performance issues on an enterprise level system - the motto 'get it done as quick as possible' seems prevalent. I have seen more Spaghetti code since the advent of Linq than I had seen with any previous class library/pattern Microsoft have released since COM.

Best Data Access Methods for New Web Application

I'm building a new web application project and am confused by the numerous methods of performing data access. I'm backending on SQL and a bit confused whether to use LINQ to SQL or trtaditional ADO.net ?
what are the advantages and disadvantages of using LINQ/SQL over ADO.net?
If it is ADO.net,then what is the best way to retrieve data means either calling the stored procedures or directly calling the t-sql code?
My question is what is cleanes and most effiecient and professional way of creating DAL for webapplication in asp.net?
Thanks
What are the advantages and
disadvantages of using LINQ/SQL over
ADO.net?
Linq2sql generates a series of
classes that are 1-to-1 mappings of
your (selected) database tables - this means you don't have to write tedious and error prone data access code
using ado.net yourself.
Linq2sql may not provide enough value for you if you intend on using a custom object-to-relational mapping (non 1-to-1) - of course you could still use linq2sql, but it would mean having an extra layer in between.
Linq2sql allows you to easily query the database using powerful linq expressions. Writing linq queries provides you with intellisense that you wouldn't get if you embedded your queries as strings inside ado.net commands, or wrote stored procs in management studio.
Using linq, you don't need to know t-sql while you will if you use ado.net (although it can definitely an advantage if your linq queries start doing strange things!). An example of this the complexity of writing t-sql queries that provide paging resultsets simply becomes .Skip(page * size).Take(size).
Linq2sql automatically creates t-sql that uses parameterised queries which is much more secure against sql injection attacks than handwritten ado.net code which builds up a query using a string.
Linq2sql doesn't work very well with stored procedures - you are probably better off not bothering with linq2sql if using sprocs.
Linq2sql could require your database tables to be less-tightly locked down than would be possible writing ado.net code using stored procedures.
If it is ADO.net,then what is the best
way to retrieve data means either
calling the stored procedures or
directly calling the t-sql code?
If you'd ruled out linq2sql, and ado.net happened to the better choice for data retrieval, I would be surprised if you were directly calling t-sql code very often or even at all. I would almost certainly expect you to be using stored procedures for reasons that you have queries that are too complex using linq, and/or security requirements.
My question is what is cleanest and most effiecient and professional way of creating DAL for webapplication in asp.net?
In my opinion, the cleanest DAL would probably use linq2sql as it is the lightest and most targeted ORM for SQL Server (assuming your still interested in SQL Server for this specific question of course).
The most efficient could be the handwritten one using ado.net, but this is probably a waste of time as more often than not, you will find a tool such as linq2sql writing better queries than 90% of developers.
In my opinion, the most professional DAL could be linq2sql, but it is more likely to be the Entity Framework of NHibernate (as other answers have suggested) due to more flexibility.
My last choice DAL in terms of cleanliness and professionalism would definitely be a handwritten ado.net one.
The best way to go is O/RM. Small apps Linq2Sql, larger apps Entity Framework 4 or NHibernate (Fluent NHibernate).
Calling SPs from your code means that your app logic is placed somewhere else than in the app code. It's a way to go but at present less and less popular because of TDD.
The best way is to create DAL into a separated logic layer, own assembly.
I would without doubt go for Linq2Sql.
Download Linqpad and play around with the included samples to get started.
You should check out some ORM frameworks, like NHibernate: http://nhibernate.info
If you want efficient data access in terms of performance than there is nothing faster than pure ADO.NET. You chan check it out here: http://ormbattle.net/.

Which is beneficial for start up; Linq to SQL or Nhibernate? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 22 days ago.
Improve this question
I want to learn ORM and I wonder which is beneficial for start up; Linq to SQL or Nhibernate. considering time,adaptation... etc
One important question to ask yourself is if you can accept a dependency on SQL Server. Will the database backend change to Oracle, for example? LINQ to SQL is strongly coupled to SQL Server, whereas NHibernate isn't. I'm not saying that this is necessarily a bad limitation, but it's important to consider.
NHibernate has really come a long way in the past few years. I really like Fluent NHibernate, for example, but that's not to say that LINQ to SQL is limiting. I love the integration with Visual Studio and it has proved itself more than capable of handling consistent load (Stack Overflow uses LINQ to SQL, for example).
Contrary to popular belief, LINQ to SQL is not dead.
Edit: Another important question to ask yourself is if you want to change the domain model. LINQ to SQL maps objects directly to tables. NHibernate, on the other hand, allows for a layer of indirection. This is also true of Entity Framework, by the way.
I'd go with NHibernate, because there's a nice open source community out there that supports it, answers questions on it, and so on. As your product gets bigger and more complicated, you'll appreciate the power and flexibility of NH. Finally, Linq-to-sql isn't in MS's long term plans, since they want you to use the Entity Framework, so you might end up with a dead-end technology there.
I would put in my vote for Linq-to-SQL - why?
it has a visual designer which allows you to more easily and quickly get results and see something
NHibernate is very powerful - but that also makes it harder to learn; you have to really really love angle bracket soup (i.e. lots of XML mapping files) to get up to speed with NHibernate
If you don't have experience with ORMs Linq to SQL is slightly easier to learn than NHibernate. It also has better integration with Visual Studio.
I love Linq to SQL, it's very easy to use. Implement the repository pattern and use LINQ to SQL as your first implementation behind your repository interface. You'll find it's so easy to get a repository up quickly using the tool. You can always implement a second repository using NHibernate without breaking your app then compare your experience with the two tools.
NHibernate is "more powerful"... I guess that means you can use it against any database, and that's about it. There's a lot more to learn and if you do go that route, make sure you make full use of Fluent NHibernate to avoid all the mapping rubbish. It's much cleaner that having a bunch of XML mappings to maintain.
I find NHibernate frustrating becuase I like querying the database with LINQ and projecting (mapping) to a model . I know there is a LINQ to NHibernate floating around, but I can't say I know anyone who uses it.
Generally, I would say to use NHibernate if you are happy to get everything by ID and traverse the object model from there. As soon as you want to execute more complex queries you had best be prepared for some frustration.
Linq to SQL is supposed to be replaced by the Entity Framework; I think NHibernate would be a good choice since there are lots of references and it seems be widely used as well.
In addition to Darin answer, Consider this post i read earlier.
Linq to SQL is easier and faster to implement and integrate quickly, but Nhibernate can give you more flexibility if you need more control. Recently, i had to decide if i was to use Linq to SQL on my new app project - i just didn't like the lack of flexibility.
NHibernate vs LINQ to SQL
http://www.acceptedeclectic.com/2007/12/linq-to-sql-vs-nhibernate-part-1-what.html
Let me know if it helps.

Categories

Resources