Best Data Access Methods for New Web Application - asp.net

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/.

Related

Create webapp with full stored procedures

I want to create a web application, all actions (Create, Update, Delete) should be done using SQL stored procedure. Every action in the web just calls a stored procedure and receives json data to render the view.
So what is the best framework that I can use? Please help
So what is the best .Net framework that I can use?
Every .Net Framework has ways to retrieve data from database. So, it doesn't really matter what version of .NET Framework you use.
I believe you would like to know what kind of library you should use for Store Procedures. If so, you might want to look at Dapper ORM.
Dapper ORM is created by Stack Exchange, and used in a lot of sites including Stack Overflow.
It basically is a wrapper around ADO.NET to map SQL result to strongly type object. If you have to do the mapping manually, it is very tedious and error prone process. So, I highly recommend using Dapper ORM if you have to call Store Procedures.

Stored procedure vs Scaffolding [closed]

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.

using linq and entity framework to iterate over database data

I read that in some books they use linq to sql and entity framework..
Whats so good about them?!!?
They are slow.. especially linq to sql. Does entity framework have any benefit that make it worth learning?!?
I strive to make the site as fast as I can, and I dont use disconnected data access much
consider that my goal is to make the site run as fast as it can
ORM frameworks like Linq-to-Sql and Entity Framework will almost always implement an abstraction layer between the program code and database SQL statement. This layer's job is to parse the code's syntax into a SQL statement.
So, if your ultimate goal is increased speed, it would be smart to avoid that layer.

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.

Resources