January 27, 2016

Entity Framework

The NuGet Gallery is the central package repository used by all package authors and consumers.



module is a set of functions, types, classes, ... put together in a common namespace.
library is a set of modules which makes sense to be together and that can be used in a program or another library.
package is a unit of distribution that can contain a library or an executable or both. It's a way to share your code with the community.
Entity Framework is ORM (Object relational mapper)

Entity Framework overview


Entity Framework Architecture

  • Extension of EF is .edmx
  • EF is directly talk with database. DAL is not required .
  • EF use ObjectContext =>DbContext interfacing with database
  • EF use EDM concept that describe the structure of data

https://msdn.microsoft.com/en-us/library/ee382825(v=vs.110).aspx


  • Entity type is class. it generate from table structure.
  • Entity type contain property and method where property is column of table and method is operation (Select/Insert/Update/Delete) done on that table
  • EF can do the operation on table with the help of LINQ or  store procedure
  • Complex object is created via Model browser if we have to call store procedure
  • Model browser - show the edmx file Model browser tab

EDM contain
  • CSDL- conceptual schema definition language
  • SSDL- storage schema definition language
  • Table Mapping - conceptual mapping and storage mapping
  • Schema contain multiple entity containers.
  • Entity container is namespace and contain entity type
  • EntityType (NavigationProperty,Scalar Property(facet),EntityKey).
  • Property contain facet (other information related to that column like Not NULL, Max length)
  • Validate - check CSDL or SSDL are synch or not
  • Complex Property
  • association - create relation between entity types

The relationship between an entity type and an entity set is analogous to the relationship between a row and a table in a relational database: Like a row, an entity type describes data structure, and, like a table, an entity set contains instances of a given structure.

Entity Framework Architecture

Setup Entity Framework Environment:


Entity Framework5


Entity Framework6




Install EF via Nuget:

Entity Framework install

Create Entity Data Model:




Entity Framework 5.0 Tutorial

Context & Entity Classes:

Entity Framework 5.0 Tutorial

Model Browser
Entity Framework 5.0 Tutorial

DBContext:

Entity Framework 5.0 Tutorial


Types of Entity in Entity Framework:

  • POCO Entity (Plain Old CLR Object):
  • Dynamic Proxy (POCO Proxy):



Entity Framework dbcontext


Entity Relationships:


Entity relationships in entity framework




entity relationships in entity framework





Entity Lifecycle:


entity states in Entity



Choose Entity Framework modling


can execute native SQL queries for a relational database

using (var ctx = new SchoolDBEntities())
{
    var studentName = ctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>();
}    

Maintain change track


Connected scenario

Entity Framework tutorial 4.3 dbcontext




using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Perform create operation
    context.Students.Add(new Student() { StudentName = "New Student" });

    //Perform Update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Perform delete operation
    context.Students.Remove(studentList.ElementAt<Student>(0));

    //Execute Inser, Update & Delete queries in the database
    context.SaveChanges();
} 

Disconnected scenario






using (var context = new SchoolDBEntities())
{
    var studentList = context.Students.ToList<Student>();

    //Add student in list
    studentList.Add(new Student() { StudentName = "New Student" });

    //Perform update operation
    Student studentToUpdate = studentList.Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();
    studentToUpdate.StudentName = "Edited student1";

    //Delete student from list
    if (studentList.Count > 0)
        studentList.Remove(studentList.ElementAt<Student>(0));

    //SaveChanges will only do update operation not add and delete
    context.SaveChanges();
}

There are two ways to go with code first approach:
  1. Data annotation
  2. Fluent API

Code First Approach using Data Annotation

Create one .cs file and give name person.cs and paste the below code into it. As this his data annotation approaches, don’t forget to add System.ComponentModel.DataAnnotation namespace.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        [Key]
        public int Id{get;set;}
        [Required]
        public string name { get; set; }
        [Required]
        public string surname { get; set; }
    }

    public class Address
    {
        [Key]
        public int personAdressId { get; set; }
        public string address { get; set; }

        [MaxLength(6)]
        public string pin { get; set; }

        [ForeignKey("Person")]
        public int PersonId { get; set; }

        //Navigation property
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext() : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}
we will specify connection string in web.config file in application. Here is code for mine.
<connectionStrings>
    <add name="DBConnectionString" 
        connectionString="Data Source=SOURAV-PC;Initial Catalog=personDB;Integrated Security=true" 
        providerName="System.Data.SqlClient"/>
  </connectionStrings>



We will implement the same model to create database using fluent API. Have a look at the below modified code of person.cs file.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp
{
    public class Person
    {
        public int Id{get;set;}
        public string name { get; set; }
        public string surname { get; set; }
    }

    public class Address
    {
        public int personAdressId { get; set; }
        public string address { get; set; }
        public string pin { get; set; }
        public int PersonId { get; set; }
        public virtual Person Person { get; set; }
    }

    public class personContext : DbContext
    {
        public personContext()
            : base("DBConnectionString")
        {
            //If model change, It will re-create new database.
            Database.SetInitializer<personContext>(new DropCreateDatabaseIfModelChanges<personContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Set primary key to Person table
            modelBuilder.Entity<Person>().HasKey(m => m.Id).Property(m => m.Id).IsRequired();
            //name fleld is required

            modelBuilder.Entity<Person>().Property(p => p.name).IsRequired();
            //surname is required
            modelBuilder.Entity<Person>().Property(p => p.surname).IsRequired();

            //set primary key to Address table
            modelBuilder.Entity<Address>().HasKey(m => m.personAdressId);

            //set max length property to 6 
            modelBuilder.Entity<Address>().Property(m => m.pin).HasMaxLength(6);

            //Set foreign key property
            modelBuilder.Entity<Address>().HasRequired(t => t.Person)
                .WithMany().HasForeignKey(t => t.PersonId);
        }
        public DbSet<Person> person { get; set; }
        public DbSet<Address> Address { get; set; }
    }
}

1 comment: