This might be a very vague question but I guess I don’t really understand what is going on. I asked a question earlier where I was told a simple way to “bind data to objects” is to just run a SqlConnection(connectionString). The response also included a comment saying I could get fancy with L2S and Entity Frameworks, so I looked deeper into those. It seems all you have to do with the DataContext object is point to the database. Why would SqlConnection be a benefit?
What is the difference (or pros/cons) of using either one of these? Is one more “standard”? Is one more modern?
P.S. I asked a lot of questions that don’t all need to be answered. I just wanted to add some clarity to my question and how much I don’t really understand this topic.
SqlConnectionis part of the base, raw ADO.NET class library – the SQL Server part of that library, really. This is the foundation of all data access in .NET.With raw ADO.NET, you’re pretty “bare-bones” and close to the metal – you have to create your SQL queries and execute them, you get back rows and columns, very much like a relational database will give you.
Pros: really close to the SQL, really powerful, best performance
Cons: harder to write, more “glue” code, less type safety, tighter coupling to the underlying database structure
DataContext(Linq-to-SQL) orObjectContext(Entity Framework) are higher level abstractions – they sit on top of ADO.NET, but they (Linq-to-SQL or Entity Framework) offer so called ORM capabilities – here, you’re not really dealing with raw SQL statements and rows/columns, instead, those code generators will create an abstraction layer for you – which is built up from .NET objects. Each table in the database will be turned into a corresponding .NET class, with properties for all the columns in that table.Also, with L2S and EF, you’re typically using
LINQto query – your queries are much more C# like code, and L2s / EF will handle translating those queries you express in C# into actual SQL statements that SQL Server will execute.Pros: much easier to work with, much nicer to handle (objects with properties vs. raw rows/columns), type safety, ability to query with LINQ, higher dev productivity
Cons: another layer means more translations, a hit on performance, not well suited for certain things (like bulk operations)