Beginner Entity Framework Code First-Part1
Published on February 13, 2013
In this post series I will explain how to create Database using EF, Configuring entities, Data Annotations, Fluent API,Data Initialization. I recommend you to download visual studio 2012 web express. If you have visual studio 2010 it is also fine. In this post we will create two tables(Posts,Comments), some sample data. Insert the sample data in Database using entity framework.
In this post, also explained how to create One-To-Many association between two entities. We will create One-To-Many association between post and Comments.(I will write more about creating association in later posts.) Introduction to Entity Framework Code First There are many definition for Entity Framework. But for me entity framework is just a library(collection of classes) written on top ADO.NET. Entity Framework allows us to deal with database directly. Entity Framework uses very simple LINQ queries to do operations on database form your .Net application.
In technology point of view Entity framework is a Microsoft’s ORM(Object Relational Mapping) product. In ORM we will create Class with properties, Each class point to the table in database where each property in a Class point to corresponding column in table. Now lets see how to create database using entity framework. Installing Entity Framework 1)Create New Empty ASP.NET Empty Web Application name it as EFDBCreation. 2)Right-Click on EFDBCreation Project and select Manage Nu Get Packages.. 3)Nu Get package manager window will be pop up now search for entity framework and click on install. 4)After install it will ask for accept for licence and a green tick mark will be shown.
Create Database using Entity framework 1)Create a new class file. 2)Name the file as BlogEntites.cs 3)Add following Code to it.
public class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public string PostBody { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentId { get; set; }
public string CommentAuthor { get; set; }
public string CommentBody { get; set; }
public virtual Post Post { get; set; }
}
Here class name Post will represents table name in DB, properties of Post Class represents column names under post table. PostId,CommentId(
public class BlogEntites : DbContext
{
public DbSet<post> Posts { get; set; }
public DbSet<comment> Comments { get; set; }
}
If you facing problem when inheriting DbContext in BlogEntites, just make sure you added using System.Data.Entites to the to BlogEntites.cs and you added EntityFramework.dll to References. 5)Now open Your web.config file and past the following code in it.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="BlogEntites"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Blog;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Blog.mdf"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
6)Now create new file default.aspx open code behind file(default.aspx.cs) and add following code inside Page_Load function
var post1 = new Post
{
PostTitle = "Post Title 1",
PostBody = "post Body 1",
Comments = new List<comment>
{
new Comment{CommentAuthor="aravind",CommentBody="my first comment on post 1"},
new Comment{CommentAuthor="dimpu",CommentBody="my second Commment on post1"}
}
};
using (BlogEntites be = new BlogEntites())
{
be.Posts.Add(post1);//post1 added in memory
be.SaveChanges();// post1 added to DB
}
In above code we creating new post object in memory and by using entity framework _Add_function,SaveChange function we adding post to DB. 7)Now Run the default.aspx Before you run make sure you added App_Data folder to the solution other wise you will get below error. If you still getting above error then add empty Blog.mdf file. 8)Now database created for you if you expand Blog.mdf as below you will notice posts,comments table created for you. Overview After all above steps your solution should look below. BlogEntites.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace EFDBCreation
{
public class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public string PostBody { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentId { get; set; }
public string CommentAuthor { get; set; }
public string CommentBody { get; set; }
public virtual Post Post { get; set; }
}
public class BlogEntites : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
}
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace EFDBCreation
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var post1 = new Post
{
PostTitle = "Post Title 1",
PostBody = "post Body 1",
Comments = new List<Comment>
{
new Comment{CommentAuthor="aravind",CommentBody="my first comment on post 1"},
new Comment{CommentAuthor="dimpu",CommentBody="my second Commment on post1"}
}
};
using (BlogEntites be = new BlogEntites())
{
be.Posts.Add(post1);//post1 added to memory
be.SaveChanges();// post1 added to DB
}
}
}
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="BlogEntites" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Blog;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Blog.mdf" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>