ASP.NET MVC is entirely independent of database access of any kind; you can pick whatever you want to use. A lot of tutorials will use Entity Framework, though, mostly because it's new and it's easy to use.
Entity Framework simplifies your data access somewhat by mapping your SQL tables to standard C# classes. If you use EF Code-First, you can even do it by defining these classes in C#, and let Entity Framework set up your database so that you never need to touch SQL. Then, because your database and the tables in it are mapped as C# classes, you can add, query, update and delete entries in your database all from C# code. The main benefits are:
- All your logic in one place, in one language. This includes defining your types/tables, querying, insert and update, everything. This makes it easier to write, easier to debug, and easier to keep it all in source control.
- Your database entities are "plain old CLR objects" (POCOs). That means you can put them in a
List<T>
, you can give them constructors to do custom initialisation, you can use inheritance to simplify their structure, clarify their relationships and take advantage of polymorphism in your code... you can do anything you can do with a regular C# class, no mapping or conversion needed.
You can use C# query syntax, either like this:
from x in table1
where x.foo == bar
select x.thing
or like this:
db.table1.x.Where(x => x.foo == bar).Select(x => x.thing);
Both give you compile-time type-checking and IntelliSense autocompletion, and both will generate equivalent SQL and only send the query to the database when you do something that needs to get the actual results, like .ToList()
.
- Entity Framework's
DbContext
class acts like a snapshot of the database, applying any changes back the the database when you call .SaveChanges()
on it. This makes it easy to use transactional access and the unit-of-work pattern, which basically means that if something goes wrong mid-operation, you can discard the whole set of changes and know that your database hasn't been messed up by a half-completed task.
There are drawbacks, mostly related to the performance penalty of taking snapshots and keeping them in sync, and the overhead of converting your C# into SQL (and sometimes it'll take more than you need into memory and do the operations there, but that can usually be avoided with a well-written query) but in many cases you won't notice the difference unless your database is enormous. For someone who's new to ASP.NET MVC, I would definitely recommend Entity Framework for database access; it'll take the hassle out of it and let you focus on the logic.