So far I’ve been working with MVC3 with Linq to Sql so that all models have been pre-generated and I would create database myself then move the tables onto the dbml editor and if I wanted to change the table I’d remove the entity on the editor and drag it on again. It works perfectly fine, but I’ve noticed that Microsoft is moving on with EF a lot, and that I should probably learn that too.
So, after reading some articles, I am totally confused. I wanted to start with Code First approach, which as I understood, makes the developer create the model for the entity first and then the model creates the database. The most confusing thing here is that when I change the model, and at the runtime when my models are being compared to the entities, if it determines that two aren’t the same, it drops all tables and recreates them. If that’s the case, how do I persist my data? How do I store all my tables so that they don’t get dropped? Should I use “Database First” approach instead?
Please help. Thanks!
You are completely right in looking at the Entity Framework instead of Linq To Sql. Microsoft focuses on EF and that’s the way to go. The Entity Framework has three options:
With database first you have an existing database that you use to create a model for you. This is done in a designer that will show you how your model looks like and where you can modify the mapping between your entities and the database.
Model first starts with an empty designer. You create your entities and then you let the Entity Framework create a database schema for it.
With Code First you don’t have a designer. Instead you create your entities in code and at runtime the Entity Framework creates a mapping from your entities to a database. This is done by some conventions (like each entity to its own table, Id properties as primary keys) and by custom mapping that you can add.
From a Linq To Sql background, the model first/database first may sound familair to you. Code First is a new way that appeals to people who want to create a clean domain model that’s purely POCO. They focus on the code, not the database.
You can experiment with all three. They all have a common base and some extra features.
Code First will have quite a lot of options when creating your database. Here you can find some info that can help getting started. The reason you see that your database is being dropped and recreated each time is because of a Database Initializer. You have several options for creating, recreating and updating your database.
In a development environment it’s probably the easiest to drop and create your database on each model change. You can also seed your database with some initial test data. In a production environment you will use Code First Migrations to migrate your database on each model change so your data is preserved.