Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Code First Approach in Entity Framework using Data Annotation and Fluent API

0.00/5 (No votes)
4 Jul 2014 2  
Various approaches of Entity Framework with examples of code first approaches

Introduction

I am planning to cover few important features of Entity Framework in a series of articles followed by this. I hope, it will help from novice to experienced .NET developers.

I expect you are already familiar with the term “Entity Framework” and want to know more about it. Then you are in the right place. Yes, entity framework is Microsoft’s ORM (Object relational mapper). I said it’s Microsoft’s product because there are many similar products in the same row from other vendors. NHibernate is one of them, which serves similar flavor. Let’s understand the term “Object relational Mapper”. Here, object is nothing but our class and relation is representing the tables which are stored in the database. Now, in previous days, developers used to write code manually to fetch data and convert the data to domain object and then pass the object across layers. Then industry started thinking to make developer’s life easy. They started to automate the mapping process by some framework which will be able to create class automatically from the database, or will be able to replicate the table as a class. So, in short, this is the purpose behind use of Entity Framework, It can automatically generate model code , takes care of SQL query and make developer’s life easy. Even if you are less familiar with the database part, Entity Framework will take care to you. Let’s come to the next discussion, how we can use Entity Framework in our application? There are three approaches to implement Entity Framework in application. We will discuss those for better understanding of future articles in this series.

Code First Approach

As the name suggests, in this approach, we will write code at first to generate database and in one good day, we will run those codes to see database in DB server. Here are a few possible scenarios where we can implement code first approach.

  • You are a hard code developer, always like to kid with code, then code first approach is fit for you
  • If you want full control over your database design without much knowledge of SQL and DBA
  • If the application is brand new and is there is no existing database for that application

So, if any one of them happens with you, you are free to go with code first approach. Truth to be told, this approach is one of the popular approaches among the three and from my personal experience, I have seen many brand new projects which have adapted this approach.

Database First

This is the next popular to code first approach. Database first approach fits best when database is created already, anyway here are few more possibilities.

  • When database already exists, you just need to develop application.
  • When the database structure is very complex and need to involve DBA professional.
  • When you are interested to work both coding and DB part of your application.
  • If you want additional features in POCO entities, you must either T4 modify template or use partial classes.
  • Manual changes in database are very easy in this approach, because it’s not directly dependent on code. Change database, update model, works smoothly.

So, those are the scenarios where database first approaches fit.

Model First

My personal experience says, this is less popular compared to code first and database first, the reason might be, developer dosen’t want to play the role of designer. Again, here are few possible scenarios when people should choose model first approach.

  • When you want to create data mode at first and share with other non-technical people. By seeing code and table, a non technical person may not understand but she might understand colorful representation of entity.
  • When your application is brand new and you are not bothering about lots of auto generate code, and you know where to tweak, if something goes wrong.

Anyway, the advantage is that, once you design the model, it will create both your class and database. Ok, so we have understood various workflows of Entity Framework and in which scenario they fit with. Now, in this post, we will discuss code first approach with example, and in consecutive article, we will go deeper into the Entity Framework.

Point to mention, there are two ways to go with code first approach:

  1. Data annotation
  2. Fluent API

Both are popular and useful, but the choice is yours. Anyway, here I will show code first approach in both ways. So, create one brand new application, I have chosen console application for demonstration, you are free to choose anything.

Code First Approach using Data Annotation

Create one .cs file and give name person.cs and paste the below code into it. As this his data annotation approaches, don’t forget to add System.ComponentModel.DataAnnotation namespace.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        [Key]
        public int Id{get;set;}
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }

    public class Address
    {
        [Key]
        public int personAdressId { get; set; }
        public string address { get; set; }

        [MaxLength(6)]
        public string pin { get; set; }

        [ForeignKey("Person")]
        public int PersonId { get; set; }

        //Navigation property
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

If you are familiar with data annotation in MVC, then I hope you are well acquainted with those attributes. The Key attribute presenting primary key of the table (We will create table by running this script shortly) The Person and Address class are very easy to understand. Just keep in mind that we have set foreign key property in Address class, which will point to primary key of Person class. Now, let’s discuss the context creation part. Have a look on personContext class definition. We have inherited it from DbContext class, in constructor we are passing “DBConnectionString” which we will define shortly in web.config file. Within constructor, we are specifying that, let's create database from scratch. If my model changes, here is the code Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

Now, we will specify connection string in web.config file in application. Here is code for mine.

<connectionStrings>
    <add name="DBConnectionString" 
        connectionString="Data Source=SOURAV-PC;Initial Catalog=personDB;Integrated Security=true" 
        providerName="System.Data.SqlClient"/>
  </connectionStrings>

The connection string is very simple. I don’t have included username and password, since I want Windows authentication to be done. In need, you can provide DB credential. Please notice that I have provided database name as “personDB”, means when my code will create database, I am expecting that name as database name. Fine, we have finished our necessary setup. Now we will run the code to seed database. Just modify the Main() function as below if you are using console application like me.

public static void Main(string[] args)
        {
            using (var ctx = new personContext())
            {
                ctx.Database.Create();
            }
        }

Now, let’s run the application and wait for the magic. Once it runs without exception (hopefully), just check your database. Here is mine.

You will see the above database structure, where two tables will create associate with all keys. So, this is the data annotation approach to create database using code first approach of entity framework.

Now, we will implement the same model to create database using fluent API. Have a look at the below modified code of person.cs file.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        public int Id{get;set;}

        public string name { get; set; }
        public string surname { get; set; }
    }

    public class Address
    {
        public int personAdressId { get; set; }
        public string address { get; set; }
        public string pin { get; set; }
        public int PersonId { get; set; }
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set primary key to Person table
            modelBuilder.Entity<Person>().HasKey(m => m.Id).Property(m => m.Id).IsRequired();
            //name fleld is required

            modelBuilder.Entity<Person>().Property(p => p.name).IsRequired();
            //surname is required
            modelBuilder.Entity<Person>().Property(p => p.surname).IsRequired();

            //set primary key to Address table
            modelBuilder.Entity<Address>().HasKey(m => m.personAdressId);

            //set max length property to 6 
            modelBuilder.Entity<Address>().Property(m => m.pin).HasMaxLength(6);

            //Set foreign key property
            modelBuilder.Entity<Address>().HasRequired(t => t.Person)
                .WithMany().HasForeignKey(t => t.PersonId);
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

Code in Main() function will remain unchanged and once we run the application, we will get the same database structure.

Border Line

As this is the first article of this series, I have discussed few basic concepts and examples. In future articles, we will focus on various topics of code first approach.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here