“Developing with code first… what a clever concept!” you may be sarcastically thinking. But in reality, we’re probably used to what’s called “Database-first” development, where we usually define the database tables before writing the code to use that data (or are given an existing dataset to work with). And this is a perfectly valid approach. Thanks to the new Entity Framework 4 (shipped with .NET 4) we can now try Code-First Development, where we define our models in code and develop against them, BEFORE the database is created. There’s a few new things that EF 4 provides that makes this a possibility:
- Data Classes no longer have to extend from specific EF base classes
- Better SQL generation (including model generation from code)
- Improved LINQ support
So here’s an example of how Code-First would work. Let’s say we have a list of products, and each product belongs to one category. First step might be to model this out, or even take a UI created by the Design team and create a ViewModel/Model for it.
1 2 3 4 5 6 7 8 9 10 11 12
Notice the lack of a base class, which was previously required by EF (and caused a bunch of issues with web service serialization). Now that we have these classes, we can create a “DbContext” that represents the EF data service.
1 2 3 4 5
The class above has a base class of DbContext, which provides all the Object Relational Mapping functionality of EF. We also use generic DbSet objects to represent collections of data of the types of models we defined above, which allow us to perform LInQ queries against them. Speaking of which, here’s an example controller method (ASP.NET MVC):
1 2 3 4 5 6 7 8 9
And that’s it! Seriously, that’s all you have to do. If you’re using a SQL Express or SQL CE database, and have the connection string setup in your app/web.config, EF 4 will actually create the database for you based on your model class definitions, ON THE FLY. When you start up the app under those conditions, EF will check the data source you’ve specified for the existance of the database, and if it’s not found it’ll automatically create it. Hell, it will even publish changes to the data model AFTER it was created! How sweet is that?