Friday 8 June 2012

Tutorial Entity Framework 4.1 - Code First


I have been looking around how to implement Entity Framework 4.1  but I have not found any nice all in one tutorial

Installing Entity Framework into  your project using nuget command:

 Use command:
      Install-Package EntityFramework

This will command will refister nuget package with your active project. It will add configuration into your target location as follows.

App.config


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" 
             type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, 
                   EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory 
             type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter 
             value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>


Definition of classes


 public class Blog
    {
        public int Id { getset; }
        public string Title { getset; }
        public List<Post> Posts { getset; } 
    }
    public class Post
    {
        public int Id { getset; }
        public string Title { getset; }
        public string Content { getset; }
        public virtual Blog Blog { getset; }
    }

Setting up DbContext



using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using EntityFrameworkCodeFirst;
 
namespace DatabLayer
{
    public class Context : DbContext
    {
        public Context()
            : base("defaultConnection")
        {
            // Get the ObjectContext related to this DbContext
            var objectContext = (this as IObjectContextAdapter).ObjectContext;
 
            // Sets the command timeout for all the commands
            objectContext.CommandTimeout = 120;
 
        }
        public DbSet<Blog> Blogs { getset; }
        public DbSet<Post> Posts { getset; }
    }
}



Program itself


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DatabLayer;
using EntityFrameworkCodeFirst;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                CreateBlog(); 
                GetNumberOfBlogs(); 
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
        private static void GetNumberOfBlogs()
        {
            var dbContext = new Context();
            Console.WriteLine("Number of existing records: {0}", dbContext.Blogs.Count());
        }
        
        private static void CreateBlog()
        {
            var blog = new Blog {Title = "testing"};
            var dbContext = new Context();
            dbContext.Blogs.Add(blog);
            dbContext.SaveChanges();
        }
    }
}



Note
If you have added new class and you have set up migrations. All changes are saved in table
"__Migrations"
In case that you edit configuration of database, EF will not let you proceed with you code saying that your migrations are not correct.
You can delete the table and it will let you continue as all records about migrations are there and it is compared to current configuration

No comments:

Post a Comment