Creating our first "Code First" application

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.

Getting ready

In order to use this recipe, you should have Visual Studio 2012 installed.

How to do it...

Here we will create a Code First application and see the main concepts behind this technology and how to use it properly.

  1. First open Visual Studio 2012 and create a new project. We will select the ASP.NET MVC 4 Web Application template from Visual C# | Web and name it EFCodeFirst as shown in the following screenshot:
    How to do it...
  2. Select the Internet Application template as shown in the following screenshot:
    How to do it...
  3. Next, we will create a class that we will use as the schema to create a table. We will add the 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; }
        }
    }
  4. In order to ensure we have the EntityFramework NuGet package, as shown in the following screenshot, we will right-click on the project and select the Manage NuGet Packages… option and validate that we have the EntityFramework package selected; if not, we will install it.
    How to do it...

    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.

  5. Right-click on the Controllers folder and select Add | Controller… as shown in the following screenshot:
    How to do it...
  6. On the Add Controller dialogue that appears, we will name the controller BooksController.
  7. On the next field, we will select the option MVC Controller with read/write actions and views, using Entity Framework.
  8. Continuing, at the Model class option we will choose the BookModel class we just created.
  9. At the Data context class option we will select the <New Data Context> option and enter the name EFCodeFirst.Models.BooksContext and click on the OK button. The dialog should look as follows:
    How to do it...
  10. We will press the Add button displayed in the previous screenshot.

    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.

  11. We will open the 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; }
    }
  12. Finally, we should be able to run the application by adding /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:
    How to do it...

How it works...

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:

How it works...

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.

There's more...

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:

  • Type discovery: This convention is used to create the database representation of our model, pulling also any referenced types. If we created a BookComments class and referenced it from our BookModel class, it would be included automatically.
  • Primary key: This is a convention that determines that a property is a primary key if it contains the id or ID string, mapping them as an integer identity column.
  • Relationship: This is a convention that infers relationships based on the navigation properties of our class. An example of this would be having the previously mentioned reference to the BookComment class set as:

    public virtual ICollection<BookComment> BookComments {get; set;}

  • Complex types: This is a convention that determines that a class with no detected primary key that does not reference other entities is a complex type.
  • Connection string: This is a convention that creates the database on the 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.

See also

Following the next recipe is recommended, since it is really important to get a solid comprehension of how Code First and Code First Migrations are used.

Additionally, I do recommend that you explore the topics, EF's conventions, Data Annotations, and fluent API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset