Book Image

Mastering Entity Framework

By : Rahul Rajat Singh
Book Image

Mastering Entity Framework

By: Rahul Rajat Singh

Overview of this book

<p>Data access is an integral part of any software application. Entity Framework provides a model-based system that makes data access effortless for developers by freeing you from writing similar data access code for all of your domain models.</p> <p>Mastering Entity Framework provides you with a range of options when developing a data-oriented application. You’ll get started by managing the database relationships as Entity relationships and perform domain modeling using Entity Framework. You will then explore how you can reuse data access layer code such as stored procedures and table-valued functions, and perform various typical activities such as validations and error handling. You’ll learn how to retrieve data by querying the Entity Data Model and understand how to use LINQ to Entities and Entity SQL to query the Entity Data Model.</p>
Table of Contents (19 chapters)
Mastering Entity Framework
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Entity Framework Code First approach


Now, let's take a look at the Entity Framework Code First approach. In this approach, we will start by creating the model classes ourselves. We will then implement our business logic against these classes, and then if we need to persist these models, we can use the Entity Framework Code First framework to save these models to the database. Thus, the Entity Framework Code First approach enables us to write simple C# classes, that is, Plain Old CLR Objects (POCOs) for our models, and then lets us persist them in a data store by defining a DbContext class for our model classes.

So, if we want to implement our ToDo application using the Code First approach, we will first have to create the ToDo model ourselves. Let's create a simple ToDo class that will keep track of our ToDo items:

public class ToDo
{
    public int Id { get; set; }
    public string ToDoItem { get; set; }
    public bool IsDone { get; set; }
}

Once we have the ToDo class ready, we need to start thinking about how the database will be created from our classes. We need to tell Entity Framework how to use our classes and generate the database accordingly. We want to tell the database generation module about all the persistence information, such as table names, key columns, and so on. We can do this in our model classes. So, if we try to put these attributes in our model class, our resultant ToDo model will look like this:

[Table("ToDo")] // Table name
public class ToDo
{
  [Key] // Primary key
      public int Id { get; set; }

  [Column("ToDoItem", TypeName="ntext")]
      public string ToDoItem { get; set; }

  [Column("IsDone", TypeName="bit")]
      public bool IsDone { get; set; }
}

In the preceding code, we updated our class with a table attribute passing in the table name. This will tell the Entity Framework that a table should be created for this class. Each property of the class can be updated with the Column attribute, and we can specify the name of the column this property should be mapped to and the data type. The Key attribute will be used to specify the property that should be used as a primary key.

Entity Framework uses the DBContext class to save the models to the database. In the Code First approach, we need to create the DBContext class ourselves too. Let's see how we can implement our DBContext class:

public partial class ToDoDBContext : DbContext
{
    public ToDoDBContext()
        : base("name=ToDoConnectionString")
    {
    }
    
    public DbSet<ToDo> ToDoes { get; set; }
}

The context class that we are creating should be derived from the DbContext class. The context class will also keep DbSet of ToDos that will represent the list of ToDo items being retrieved from the table. The constructor of the context class will pass the name of connectionString to the base DbContext class. This connectionString will be used to connect to the database.

Another possibility is to keep the name of the connectionString the same as the DbContext class name. The Entity Framework will be able to use the corresponding DbContext class with this connectionString to persist the data. This is an example of the Convention over configurations principle. However, this is also flexible, so that we have the possibility of giving custom names to the connectionStrings.

Now to be able to use Entity Framework to persist the data, we just need to create this connectionString in the XML configuration, and Entity Framework will take care of creating the database and performing the CRUD operations on their respective models.

This has shown you how to use the Code First approach using a single model. In later chapters, you will see how to use multiple models and have relationships between them, how we can define complex types, and customize models as per our application requirements.

We have looked at how Entity Framework supports various development approaches and lets us create the conceptual model and data access logic very easily. We have seen that Entity Framework depends on the EDM to perform the database CRUD operations, and we have also looked at the various ways to create the conceptual model and map it to the database using the Database First, Model First, and Code First approaches.

To fully understand the benefits of Entity Framework over ADO.NET, we must also look at how easy and efficient it is to use Entity Framework to perform the actual operations. This will also show how performing CRUD operations is the same, irrespective of the approach we take. Let's now see how we can perform CRUD operations using Entity Framework to fully understand the benefits of Entity Framework.