Entity Framework Code First from Scratch

Introduction:

Entity Framework is Microsoft's latest data access technology. Entity framework is an ORM that is used to interect with relational databases. ORM stands for Object Relational Mapper. Entity framework has few approaches to interect with database that are:

  • Code First
  • Model First
  • Database First

Code First Approach:

Here we are going to learn Code First from scratch in console application. There are a few things you must know before working on the entity framework Code First approach. Entiry framework code classes are just classes. You can make an entity framework code class by using the normal way to add classes to your project.

Code First Conventions:

There are few conventions used by the Code First model, which means entiry framework has some rules that it follows while working with code classes. Conventions are given here.

  • Tables are automatically pluralized.
  • If you create a class and add a property with the same name of class and append ID at the end with this property entity framework will consider this property a “ Primary Key. ”
  • Primary key of Table ( class ) built by entity framework is auto incremented by default.

Location of Database :

Entiry framework can create your database on cloud , App_Data folder of your application, intranet or internet etc. Entity framework will decide the location of your physical database upon a few factors like availability of local or online server, etc.

Data Annotations and Attributes in Code First:

Attributes are the instructions for the database table or the columns inside those tables. I’m showing you a few attributes that are commonly used in Code First to maintain database .

  • Name :

    Name attribute is used to explicitely set the name for table or column of table.
    for example in the following table( class ) default name for the table was,  
    1. [Key]  
    2. public int ID   
    3. {  
    4.     get;  
    5.     set;  
  • String Attributes

    One of the important points of strings in .net is that strings are reference type which means they can be null, so entity framework shows a default behavior on reference types and set them in database columns as "nullable"( allow nulls = true ). To prevent this behavior for nullable types, use the attribute “ [ Required ]."
    1. [Required]  
    2. publicstring Name  
    3. {  
    4.     get;  
    5.     set;  
    6. }  
    If you do not write “ Required"  with column name of datatype string, entiry framework will create a table column with nullable and varchar datatype.

  • Number Attributes

    Numbers are value type in .net, so they need to have "values." Entity framework will not
    set them as nullable. So what you'll do if you want to have a nullable number on Table is, 
    you’ll use the nullable datatypes in C#. see the following column. (See question mark.)
    1. public int ? Marks  
    2. {  
    3.     get;  
    4.     set;  
    5. }  
  • Range Attributes

    You can use the Range Attribute to set the range of numerical data in code
    classes. And same thing you can do with strings in Code classes.
    1. [MaxLength(30)]  
    2. [MinLength(2)]  
    3. public int? Marks   
    4. {  
    5.     get;  
    6.     set;  
    7. }  
    8.   
    9. [MaxLength(30)]  
    10. [MinLength(10)]  
    11. [Required]  
    12. public string Name   
    13. {  
    14.     get;  
    15.     set;  
    16. }  

Code First Migrations:

Its important to upgrade your database, whenever the model ( code classes ) in application changes. In order to upgrate the database, we use Database migrations in entiry framework . I’ll explain this in my upcoming article. Because here, I’m going to show you a very simple demo of code first with Console Application.

Example:

In this example we will make a database table using entiry framework code first approach and then perform CRUD operation on that table. CRUD stands for Create, Read, Update, Delete. Other database operations like building many to many and one to many relations etc, will be described later. So let's get started.

  1. Make a new Console Application of C# in Visual Studio.
  2. Make a class with name Student as given below.

    a. Put two properties ( These propeties will be the names for columns ).
    1. public class Student   
    2. {  
    3.     public int StudentId  
    4.     {  
    5.         get;  
    6.         set;  
    7.     }  
    8.     public String Name  
    9.     {  
    10.         get;  
    11.         set;  
    12.     }  
    13. }
  3. It's time to create a database which will contain your table also. Make a class with name “StudentDb” and inherit it with “DbContext”. You’ll receive an error while performing this task because you’ve not added entityframework reference yet.
    1. public class StudentDb : DbContext  
    2. {  
    3.     public DbSet < Student > students  
    4.     {  
    5.         get;  
    6.         set;  
    7.     }  
    8. }  
  4. Installing Entity Framework:

    To install entity framework into your solution open …
    Tools > Nuget Package Manager > Manage Nuget packages for Solution.

    install

  5. Select browse then type “Entity framework” in search box. All related items will appear in search results. Select Entity framework. Entity framework details will appear. Now you’ll be given an option to select the solutions and projects on which you want to install EF ( EF used for entiry framework ). As you check the project checkbox at number 4 in picture, Button “Install” will be enabled. Click install and proceed.

    entity framework

  6. A preview of the framework and the Target project will be shown to you. Press ok
    and proceed.

    preview

  7. License Acceptance window will appear. Click “I Accept” and after that Entity framework will be installed to your project.You may see the installed packages by opening the References in Solution Explorer.

    license

  8. Insert Data:

    Its time to add some data into your project.

    [Note: Until now you only desinged your data; this database will be created once you run your program.]

    Add following code into Main() function to insert data into table.
    1. staticvoid Main(string[] args)  
    2. {  
    3.     using(var db = newStudentDb()) // object of Database ( context class )  
    4.         {  
    5.             Student stu = new Student(); // student table object  
    6.   
    7.             Console.WriteLine("Name : ");  
    8.             stu.Name = Console.ReadLine(); // use object.Property to assign data.  
    9.   
    10.             // Data Insertion into database.  
    11.             db.students.Add(stu);  
    12.             db.SaveChanges();  
    13.             Console.WriteLine("Data has been inserted successfully");  
    14.         }  
    15. }  
  9. Press F5 to run your program. The first time this program will take more time to run because in the background, entity framework is creating a database and adding tables for us. Give some input name to save into table and press enter. You’ll see the message “data has been inserted successfully.”

    output

  10. Retrieve Data:

    Data has been saved into the database . Now we’ll perform the secind operation in CRUD which is Read or Retrieve. Update your Main() method with the following code to fetch the recently inserted data from Student Table and press F5 to run the program.
    1. staticvoid Main(string[] args)  
    2. {  
    3.     using(var db = newStudentDb()) // Object of Database ( context class )  
    4.         {  
    5.             var queryResult = (from s in db.students 
                                     select s).ToList();  
    6.   
    7.             foreach(var item in queryResult) 
                  {  
    8.                 Console.WriteLine("Name : {0}", item.Name);  
    9.             }  
    10.         }  
    11.     Console.ReadLine();  
    12. }  

    output

  11. Update Data:

    To update data write the following code into Main() method.and run the code. Here I’m just updating the name of student. In order to update some data you must select the row from table which you want to update, so first we’ll fetch the row and update its record.
    1. staticvoid Main(string[] args)  
    2. {  
    3.     using(var db = newStudentDb()) // Object of Database ( context class )  
    4.         {  
    5.             var queryResult = db.students.First(s => s.Name == "Ammar Shaukat");  
    6.             queryResult.Name = "New Name for Ammar";  
    7.             db.SaveChanges();  
    8.             Console.WriteLine("Data has been updated");  
    9.         }  
    10.     Console.ReadLine();  
    11. }  
  12. Delete Data:

    And in the same way you can delete your data too. Just update the Main() method will following code.and run the program.

    Remove() method is used to remove a row from database table in entity framework.
    1. using(var db = newStudentDb()) // Object of Database ( context class )  
    2.     {  
    3.         var _student = db.students.First(s => s.Name == "Ammar Shaukat");  
    4.         db.students.Remove(_student);  
    5.         db.SaveChanges();  
    6.         Console.WriteLine("Data has been Deleted");  
    7.     }  
    This was the simple CRUD operation using Entity framework. In my next article I’ll show you the making of “One to many relationship” and “Many to many relationship” using Code first.

    I’ll wait for your feedback. I’m new to writing articles. If this article helped you please mention in comments or ping me.


Similar Articles