Monday, June 1, 2015

Simple Code First Example

To begin with code first, let us try to create a single table in the database. You just have to code the following.

1. A class file which is a representation of your business layer. i.e, Add a class with  column names of your table as properties of the class.

For MVC Applications, Right click on the models folder and select "Add -> ADO .NET Entity data model" and give a name for your model. You can create the following class within the model file. For other types of applications (other than MVC), simply add a class file to your project.

    public class Parent
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Here, "Parent" is the table name and "Id" &"Name" are the table columns.

2. A context file that inherits from "DbContext". DbContext is a built-in class of Entity Framework that helps us to query the database  and interact with it. 

    public class SampleContext : DbContext
    {
        public SampleContext()
            : base("name=DefaultConnection")
        {
        }
        public DbSet<Parent> Parents { get; set; }
    }

Here, we are passing "DefaultConnection" to the constructor which is the name of the connection string in web.config file. Web.config will be auto-generated for MVC internet applications. You can also specify your own database instead of default connection as mentioned here. For other applications you can add your own connection string in web.config file and pass the name of the connection in the constructor. Instead of giving "name=", you can directly pass the database name to the constructor (:base("sample")) or you can also leave it empty. If you don't specify anything, a database with name {namespace}.{context class name} will be created in your local SQLEXPRESS.

We have added another property called "Parents" to the context class and note that it is returning DbSet<parent>. This property is going to help us in querying the database. "DbSet" is a collection of entity set. In this case, "Parent" is our entity. You will be more clear when we actually use this property.


Now we are done with our model creation. We just have to create an instance of context class and then we can start interacting with the database.

   public void Create()
   {
       SampleContext db = new SampleContext();    
       Parent parent = new Parent(){Name="XYZ"};
       db.Parents.Add(parent)
       db.SaveChanges();
   }

Add the above code to your controller (for MVC) or main method(for other applications). First, we are creating an instance of context class. Then, collecting the data that we want to save to the database. In the next step, we are using the "parents" property created in the context class to add the values to the database and finally saving it.

Once you run your project you can see the table created in your database.


Table with name "Parents" has been created in the database(Table name is automatically pluralized by entity framework). Without any ado .net code, we have created our table with the help of entity Framework code first approach !!


No comments:

Post a Comment