Our first application will create a database from code. We will start by creating an ASP.NET project that we will reuse in the following recipes.
Here we will create a Code First application and see the main concepts behind this technology and how to use it properly.
EFCodeFirst
as shown in the following screenshot:BookModel
class to the Models
folder of our project as shown in the following code. Note that we will need to add a reference to System.ComponentModel.DataAnnotations.
namespace EFCodeFirst.Model { public class BookModel { [Required] public int Id { get; set; } public String Title { get; set; } public String Description { get; set; } } }
We will build the project before continuing, so that everything is up-to-date. If not, we will not be able to see the classes we just created in the template dialog.
BooksController
.EFCodeFirst.Models.BooksContext
and click on the OK button. The dialog should look as follows:As a result, the BooksController.cs
and BooksContext.cs
files will be added with methods to handle data, together with a view
folder containing some files for each needed view.
BooksContext
file to see how simple it would be to create this class on our own, should we need it for other projects without the autogeneration help that this tooling provides:public class BooksContext : DbContext { // You can add custom code to this file. Changes will not be overwritten. // // If you want Entity Framework to drop and regenerate your database // automatically whenever you change your model schema, add the following // code to the Application_Start method in your Global.asax file. // Note: this will destroy and re-create your database with every model change. // // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<EFCodeFirst.Models.BooksContext>()); public BooksContext() : base("name=BooksContext") { } public DbSet<BookModel> BookModels { get; set; } }
/books
to our URI, for instance http://localhost:5049/books
, so that we can start creating our book collection as shown in the following screenshot:We created an ASP.NET application as a placeholder to showcase the EF capabilities, but we could have chosen other options, such as a console application.
The first step was creating a basic class with some properties that we want to use to create a database table. Continuing, we validated that we had the EntityFramework NuGet package so that we could properly work with EF Code First.
Next, we added a controller that was automatically created for our BooksModel
class, creating all of the tools that are necessary for MVC to work with the data. This automates for us the creation of the data context for the DbContext
base class.
Additionally, in the BooksContext.cs
file we can observe that we have a reference to the System.Data.Entity
namespace. If we were to create this manually, we would also need to add this reference manually. This context is all the code we need to store and retrieve data; a DbSet
property of the entity type inside this context class is shown in the following code:
public DbSet<BookModel> BookModels { get; set; }
Of course, we will need to create an instance of the context class, which DbContext
will use to create a LocalDB
database for us (this is installed by default by Visual Studio 2012). The database is named after the fully qualified name of our context, as we can see in the following screenshot:
The DbContext
class then looks at the properties and uses the DbSet
properties that we have defined to create the tables, fields, and other properties.
We have just grasped the power of Entity Framework Code First, but there's much more than we have seen.
This release is especially powerful in its ability to deal with model changes, and with it we can go ahead or back in time in a proper way. We will see how this works in the next recipe.
We have the Code First conventions that EF uses to discover the model, which are type discovery, primary key, relationship, complex types, and connection string, explained in the following list:
BookComments
class and referenced it from our BookModel
class, it would be included automatically.id
or ID
string, mapping them as an integer identity column.BookComment
class set as:
public virtual ICollection<BookComment> BookComments {get; set;}
LocalDB
Server, naming it after the fully qualified name of the context.The Code First conventions can be extended by Data Annotations, which are attributes that enable further configuration. Among other things, we can identify a field as a key or foreign key or mark that a field is required, as we did in our BookModel
class. Note that we, in practice, override almost all of the conventions with these Data Annotation attributes.
For example, it would be clearer if, in our class, we put the [Key]
attribute in our key field:
[Key] public int Id { get; set; }
These Data Annotations are useful to supplement the conventions or to directly override them.
We also have a fluent API, which gets us into the advanced part of Code First, and thus it is recommended that we use it only in those situations where Data Annotations can't help us. With fluent API, we can override the OnModelCreating
method in the DbContext
base class and configure the properties with more capabilities than with the conventions or Data Annotations model.
Of course we can use all these models combined in any way we wish, getting the best of all worlds.