Friday, 6 January 2017

Create a Code First Model in Entity Framework

In this post we are going to see how to create a Code First Approach in entity framework, First we create a MVC project, then right click on solution explorer click on Manage Nuget Packages, Search for Entity Framework, then click install the latest package, Then we are to start coding for Code First.


Now we are going to create a Model for the Tables, Let we take some example like Employee, Department, Task. 


    public class Employee
    {
        public Employee()
        {
            Tasks = new List<Task>();
        }

        public string Name { set; get; }

        public int Id { set; get; }

        public int Contact { set; get; }

        public string Address { set; get; }

        public int Salary { set; get; }

        public int DepartmentId { set; get; }
        
        public virtual ICollection<Task> Tasks { set; get; }


    }


    public class Department
    {
        public int Id { set; get; }

        public string Name { set; get; }

    }


    public class Task
    {
        public int Id { set; get; }

        public string Name { set; get; }

        public string Description { set; get; }

    }


Next we have to create a Class which derives from DbContext, then we have to specify the models with the DbSet<Type> then only it will create as Table, even to create the table atleast you have to invoke the instance of this class atleast once,



    public class EmployeeDbContext:DbContext
    {
        public EmployeeDbContext()
        {
            this.Configuration.AutoDetectChangesEnabled = true;
            this.Configuration.LazyLoadingEnabled = true;
           
        }

        public DbSet<Employee> Employees { set; get; }

        public DbSet<Department> Departments { set; get; }

        public DbSet<Task> Tasks { set; get; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }


now we have to specify the connection string for the EF, in the same name of EmployeeDbContext and specify the Connecting string, here in code first approach we have to specify the Provider name in the connecting like System.Data.SqlClient, then only it will create tables otherwise raise error


  <connectionStrings>
    <add name="EmployeeDbContext"
         connectionString="Server= SQLEXPRESS;Database=EFDB;Integrated Security=true;"                 providerName="System.Data.SqlClient"/>

  </connectionStrings>


Below is the sample Tables created in the DB.




If you change something in the above in the model class for example adding Department id as Foreign key, then we have to create a property with the Department type then add a ForeignKey attribute then specify the exact column name which uses to refer DepartmentId,


    public class Employee
    {
        public Employee()
        {
            Tasks = new List<Task>();
        }

        public string Name { setget; }

        public int Id { setget; }

        public int Contact { setget; }

        public string Address { setget; }

        public int Salary { setget; }

        public int DepartmentId { setget; }

        [ForeignKey("DepartmentId")]
        public virtual Department Department { setget; }

        public virtual ICollection<Task> Tasks { setget; }


    }


Now if  you run the application it will raise a error like below, to resolve the error we have to initialize the Database, here we are Initialize with some sample data.











    public class EmployeeDbInitializer : DropCreateDatabaseIfModelChanges<EmployeeDbContext>
    {
        protected override void Seed(EmployeeDbContext context)
        {
            Department depart = new Department() { Id = 1,Name = "Development"};

            Employee testEmployee = new Employee() {  
                     Id =101,Name="Test",Contact=234234324,DepartmentId = 1 };

            context.Departments.Add(depart);
            context.Employees.Add(testEmployee);           
            base.Seed(context);
        }

    }



    public class EmployeeDbContext:DbContext
    {
        public EmployeeDbContext()
        {
            this.Configuration.AutoDetectChangesEnabled = true;
            this.Configuration.LazyLoadingEnabled = true;
            Database.SetInitializer(new EmployeeDbInitializer());
        }

        public DbSet<Employee> Employees { set; get; }

        public DbSet<Department> Departments { set; get; }

        public DbSet<Task> Tasks { set; get; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }





Again Run the Website now you can able to see the changes in the DB like below.










From this post you can learn how to create a Code First Creation of Entity Framework





No comments:

Post a Comment