Monday, November 26, 2018

পার্ট 11 - Entity splitting in entity framework with code first approach

Suggested Articles
পার্ট 8 - Using stored procedures with the entity framework code first approach
পার্ট 9 - Overriding stored procedure defaults with the entity framework code first approach
পার্ট 10 - Entity splitting in entity framework (DB_First Approach)

যখন দুই বা ততোধিক Database টেবিলের মধ্যে একটা common key শেয়ার হয় তখন, Entity Framework এর Entity splitting এই feature টি একটা entity কে সেই দুই বা ততোধিক Database টেবিলের সাথে mapping করে দেয়। আগের পর্বে আমরা Entity Framework এর Entity splitting feature টা database first approach এ আলোচনা করেছিলাম, এই আর্টিকেলে আমরা Entity splitting feature কে code first approach এ আলোচনা করবো।

N.B: Practical ধাপগুলো আমি আপনাদের বোঝার সুবিধার জন্য English এ explain করবো। এই step গুলো VS2017(Visual Studio 2017) এ execute করা হয়েছে।

Step 1: Create a new empty asp.net web application project. Name it Demo. Install entity framework if it's not already installed.

Step 2: Add a class file to the project. Name it Employee.cs. Copy and paste the following code.
namespace Demo
{
    public class Employee
    {
        // These property values should be stored in Employees Table
        public int EmployeeId { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Gender { getset; }

        // These property values should be stored in EmployeeContactDetails Table
        public string Email { getset; }
        public string Mobile { getset; }
        public string Landline { getset; }
    }
}

Step 3: Add a class file to the project. Name it EmployeeDBContext.cs. Copy and paste the following code.
using System.Data.Entity;
namespace Demo
{
    public class EmployeeDBContext : DbContext
    {
        public DbSet<Employee> Employees { getset; }
    }
}

Step 4: Add a class file to the project. Name it EmployeeRepository.cs. Copy and paste the following code.
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
    public class EmployeeRepository
    {
        EmployeeDBContext employeeDBContext = new EmployeeDBContext();

        public List<Employee> GetEmployees()
        {
            return employeeDBContext.Employees.ToList();
        }

        public void InsertEmployee(Employee employee)
        {
            employeeDBContext.Employees.Add(employee);
            employeeDBContext.SaveChanges();
        }

        public void UpdateEmployee(Employee employee)
        {
            Employee employeeToUpdate = employeeDBContext.Employees
                .SingleOrDefault(x => x.EmployeeId == employee.EmployeeId);
            employeeToUpdate.EmployeeId = employee.EmployeeId;
            employeeToUpdate.FirstName = employee.FirstName;
            employeeToUpdate.LastName = employee.LastName;
            employeeToUpdate.Gender = employee.Gender;
            employeeToUpdate.Email = employee.Email;
            employeeToUpdate.Mobile = employee.Mobile;
            employeeToUpdate.Landline = employee.Landline;

            employeeDBContext.SaveChanges();
        }

        public void DeleteEmployee(Employee employee)
        {
            Employee employeeToDelete = employeeDBContext.Employees
                .SingleOrDefault(x => x.EmployeeId == employee.EmployeeId);
            employeeDBContext.Employees.Remove(employeeToDelete);
            employeeDBContext.SaveChanges();
        }
    }
}

Step 5: Add the database connection string in web.config file.
<connectionStrings>
  <add name="EmployeeDBContext"
        connectionString="server=.; database=Sample; integrated security=SSPI;"
        providerName="System.Data.SqlClient" />
</connectionStrings>

Step 6: Add a webform to the project. Drag and drop the following 3 controls and build the solution.
1. GridView
2. DetailsView
3. ObjectDataSource

Step 7: Configure ObjectDataSource control
a) Right click on ObjectDataSource control and select "Show Smart Tag" option
b) Click on Configure Data Source link
c) Select Demo.EmployeeRepository on Choose a Business Object screen and click Next
d) On Define Data Methods screen
i) On SELECT tab - Select GetEmployees() method
ii) On UPDATE tab - Select UpdateEmployee(Employee employee) method
iii) On INSERT tab - Select InsertEmployee(Employee employee) method
iv) On DELETE tab - Select DeletEmployee(Employee employee) method

Step 8: Configure GridView control
a) Right click on GridView control and select "Show Smart Tag" option
b) Click on "Auto Format" link and select "Colourful" scheme
c) Select "ObjectDataSource1" from "Choose Data Source" drop-down list
d) Select Enable Editing and Enable Deleting checkboxes
e) Set DataKeyNames="EmployeeId". Do this in the properties window of the GridView control
f) Set ReadOnly="true" for the EmployeeId BoundField. You can do this directly in the HTML Source.

Step 9: Configure DetailsView control
a) Right click on DetailsView control and select "Show Smart Tag" option
b) Click on "Auto Format" link and select "Colourful" scheme
c) Select "ObjectDataSource1" from "Choose Data Source" drop-down list
d) Select Enable Inserting checkbox
e) Set DeafultMode=Insert. Use properties window to set this.
f) Set InsertVisible="false" for the EmployeeId BoundField. You can do this directly in the HTML Source.
g) Generate ItemInserted event handler method for DetailsView control. Copy and paste the following code.
protected void DetailsView1_ItemInserted(object senderDetailsViewInsertedEventArgse)
{
    GridView1.DataBind();
}


Step 10: If you already have Sample database in SQL Server. Delete it from SQL Server Management Studio.

Step 11: Run the application by pressing CTRL + F5. By default, entity framework creates one Table i.e Employees table. But we want entity framework to create the following 2 tables.
a) Employees table with columns EmployeeId, FirstName, LastName, and Gender
b) EmployeeContactDetails table with columns EmployeeId, Email, Mobile and Landline

Step 12: Override OnModelCreating() method to tell entity framework to generate 2 tables(Employees & EmployeeContactDetails) for the Employee entity. OnModelCreating() method is a virtual method present in DbContext class. So, modify EmployeeDBContext class in EmployeeDBContext.cs file as shown below.
public class EmployeeDBContext : DbContext
{
    public DbSet<Employee> Employees { getset; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
        // Specify properties to map to Employees table
        .Map(map =>
        {
            map.Properties(p => new
            {
                p.EmployeeId,
                p.FirstName,
                p.LastName,
                p.Gender
            });

            map.ToTable("Employees");
        })
        // Specify properties to map to EmployeeContactDetails table
        .Map(map =>
        {
            map.Properties(p => new
            {
                p.EmployeeId,
                p.Email,
                p.Mobile,
                p.Landline
            });

            map.ToTable("EmployeeContactDetails");
        });

        base.OnModelCreating(modelBuilder);
    }
}

Step 13: Delete the Sample database and run the web application.

Step 14: Notice that now we have 2 tables generated by entity framework as expected.
 Entity splitting in entity framework with code first approach
2 Tables Generated by Entity Framework


Step 15: Execute the following SQL script to populate the tables with test data.

Insert into Employees values ('Mark', 'Hastings', 'Male')
Insert into Employees values ('Steve', 'Pound', 'Male')
Insert into Employees values ('Ben', 'Hoskins', 'Male')
Insert into Employees values ('Philip', 'Hastings', 'Male')

Insert into Employees values ('Mary', 'Lambeth', 'Female')

Insert into EmployeeContactDetails values
(1, 'Mark@pragimtech.com', '111111111', '111111111')
Insert into EmployeeContactDetails values
(2, 'Steve@pragimtech.com', '2222222222', '2222222222')
Insert into EmployeeContactDetails values
(3, 'Ben@pragimtech.com', '3333333333', '3333333333')
Insert into EmployeeContactDetails values
(4, 'Philip@pragimtech.com', '44444444444', '44444444444')
Insert into EmployeeContactDetails values

(5, 'Mary@pragimtech.com', '5555555555', '5555555555')

Step 16: At this point run the application. Insert, update and delete an Employee, and notice that both the tables (Employees and EmployeeContactDetails) are updated as expected.

Output Should be look like following..
Entity splitting in entity framework with code first approach
WebForm Output


উপরের explanations আরও ভালভাবে বুঝতে এই video টি একবার দেখে আসুন। ধন্যবাদ।।






Saturday, November 24, 2018

পার্ট 2 - C# টিউটোরিয়াল - Reading and writing to a console

Suggested Articles
Part 1 - Introduction to C#

আমরা এই আর্টিকেলে একটা demo program এর মাধ্যমে দেখবো -

1. console এর সাহায্যে কিভাবে read করা হয়
2. console এর সাহায্যে কিভাবে write করা হয়
3. console এ write করার দুইটা way আছে-
                           a) Concatenation
                           b) Placeholder syntax – Most preferred

Demo Code-
using System;
class Program
{
    static void Main()
    {
        // Prompt the user for his name
        Console.WriteLine("Please enter your name");

        // Read the name from console
        string UserName = Console.ReadLine();

        // Concatenate name with hello word and print
        Console.WriteLine("Hello " + UserName);

        //Placeholder syntax to print name with hello word 
        //Console.WriteLine("Hello {0}", UserName);
    }
}

N.B: C# কিন্তু একটা case sensitive language



পার্ট 2 - C# টিউটোরিয়াল - Reading and writing to a console




Wednesday, November 21, 2018

পার্ট 10 - Entity splitting in entity framework (DB_First Approach)

Suggested Articles
পার্ট 7 - Using stored procedures with entity framework
পার্ট 8 - Using stored procedures with the entity framework code first approach
পার্ট 9 - Overriding stored procedure defaults with the entity framework code first approach

Entity Framework এর Database First approach এ যখন দুই বা ততোধিক Database table একটা common key শেয়ার করে, তখন Entity mapping এর সাহায্যে কিভাবে Entity splitting করা যায় সে বিষয়ে আলোচনা করবো। চলুন একটা উদাহরণ দিয়ে দেখা যাক -

আমদের কাছে ২ টা table আছে। এই দুই টেবিলই একটা common key শেয়ার করে তার নাম EmployeeID

Entity splitting in entity framework
EmployeeContactDetails Table

Entity splitting in entity framework
EmployeeContactDetails Table 

টেবিল ২ টা create করে এদের test data দিয়ে populate করার জন্য SQL Script -
Create table Employees
(
     EmployeeID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50)
)
GO

Create table EmployeeContactDetails
(
     EmployeeID int primary key,
     Email nvarchar(50),
     Mobile nvarchar(50),
     LandLine nvarchar(50),
     CONSTRAINT fk_pk_empid FOREIGN   KEY(EmployeeIDREFERENCES  Employees (EmployeeID)
)
GO

Insert into Employees values ('Mark', 'Hastings', 'Male')
Insert into Employees values ('Steve', 'Pound', 'Male')
Insert into Employees values ('Ben', 'Hoskins', 'Male')
Insert into Employees values ('Philip', 'Hastings', 'Male')
Insert into Employees values ('Mary', 'Lambeth', 'Female')

Insert into EmployeeContactDetails values
(1, 'Mark@pragimtech.com', '111111111', '111111111')
Insert into EmployeeContactDetails values
(2, 'Steve@pragimtech.com', '2222222222', '2222222222')
Insert into EmployeeContactDetails values
(3, 'Ben@pragimtech.com', '3333333333', '3333333333')
Insert into EmployeeContactDetails values
(4, 'Philip@pragimtech.com', '44444444444', '44444444444')
Insert into EmployeeContactDetails values
(5, 'Mary@pragimtech.com', '5555555555', '5555555555')

এখন যদি আমরা  Entity Framework এর database first approach এ entity generate করি তাহলে by default ২ টা entities create হবে। i.e Employee এবং EmployeeContactDetail entities -
Entity splitting in entity framework
EmployeeModel.edmx
এখন আমরা Employee নামের একটা entity চাই যেটা Employees এবং EmployeeContactDetails নামের দুইটা টেবিলকেই map করবে।

To achieve this 
1. Cut Email, Mobile and LandLine properties from the EmployeeContactDetail entity and paste them in Employee entity.
2. Delete EmployeeContactDetail entity. On "Delete Unmapped Tables and Views" window click NO.
3. Right click on the Employee entity and select "Table Mapping" option from the context menu. Map EmployeeId, Email, Mobile and LandLine properties to the respective columns of EmployeeContactDetails table.
Entity splitting in entity framework-Table Mapping
Table Mapping

At this point, we have only one Entity. Build the solution. Add a WebForm. Drag and drop the following 3 controls.
1. GridView
2. DetailsView
3. EntityDataSource

Configure EntityDataSource control
a) Right click on EntityDataSource control and select "Show Smart Tag" option
b) Click on Configure Data Source link
c) Select EmployeeDBContext from the Named Connection drop-down list and click Next
d) Select Employees from EntitySetName drop-down list and enable Inserts, Updates, and Deletes.

Configure GridView control
a) Right click on GridView control and select "Show Smart Tag" option
b) Click on "Auto Format" link and select "Colourful" scheme
c) Select "EntityDataSource1" from "Choose Data Source" drop-down list
d) Select Enable Editing and Enable Deleting checkboxes

Configure DetailsView control
a) Right click on DetailsView control and select "Show Smart Tag" option
b) Click on "Auto Format" link and select "Colourful" scheme
c) Select "EntityDataSource1" from "Choose Data Source" dropdownlist
d) Select Enable Inserting checkbox
e) Set DeafultMode=Insert. Use properties window to set this.
f) Set InsertVisible="false" for the EmployeeID BoundField. You can do this directly in the HTML Source.
g) Generate ItemInserted event handler method for DetailsView control. Copy and paste the following code.
protected void DetailsView1_ItemInserted
                                 (object sender, DetailsViewInsertedEventArgs e)
{
GridView1.DataBind();
}

At this point run the application. Insert, update and delete an Employee, and notice that both the tables (Employees and EmployeeContactDetails) are updated as expected.

webForm should look like following-
Entity splitting in entity framework - Output
webForm1


উপরের explanations আরও ভালভাবে বুঝতে এই video টি একবার দেখে আসুন। ধন্যবাদ।।



Monday, November 19, 2018

পার্ট 9 - Entity framework এর code first approach এ default stored procedure গুলোকে overriding করা

Suggested Articles
পার্ট 6 - How to seed the database with test data using entity framework
পার্ট 7 - Using stored procedures with entity framework
পার্ট 8 - Using stored procedures with the entity framework code first approach

Entity framework এর code first approach এ যে stored procedure গুলো তৈরি হয় (Insert, Update এবং Delete stored procedure) সেগুলোর কিভাবে পরিবর্তন করা যায় তা নিয়ে discuss করবো এই আর্টিকেলে। এই আর্টিকেলটি পার্ট 8 এর continuation, তাই এই আর্টিকেলটি শুরু কারার আগে পার্ট 8 এ একবার চোখবুলিয়ে আসুন।


public class EmployeeDBContext : DbContext
{
    public DbSet<Employee> Employees { getset; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().MapToStoredProcedures();
        base.OnModelCreating(modelBuilder);
    }
}

By default, উপরের code, Employee objects গুলোকে Insert, Update এবং Delete করার জন্য নিচের ৩ টি stored procedures তৈরি করে -
Employee_Insert
Employee_Update
Employee_Delete

আপনি যদি auto-generated এই stored procedures গুলোর default name কে override অথবা change করতে চান তাহলে EmployeeDBContext class এর code গুলোকে নিচের code এর মতো পরিবর্তন করতে হবে -

public class EmployeeDBContext : DbContext
{
    public DbSet<Employee> Employees { getset; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
            .MapToStoredProcedures(p => p.Insert(x => x.HasName("InsertEmployee")));
        modelBuilder.Entity<Employee>()
            .MapToStoredProcedures(p => p.Update(x => x.HasName("UpdateEmployee")));
        modelBuilder.Entity<Employee>()
            .MapToStoredProcedures(p => p.Delete(x => x.HasName("DeleteEmployee")));

        base.OnModelCreating(modelBuilder);
    }
}

এখন Sample database টা delete করে দেন এবং WebForm1 কে run করুন। দেখা যাবে generated stored procedures গুলোর নাম আমাদের specify করে দেয়া নাম অনুসারে হয়েছে -
Entity framework এর code first approach এ default stored procedure গুলোকে overriding করা
Names of the generated SP
উপরের code গুলোকে নিচের মতো করেও লেখা যায় -

public class EmployeeDBContext : DbContext
{
    public DbSet<Employee> Employees { getset; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().MapToStoredProcedures
            (p => p.Insert(i => i.HasName("InsertEmployee"))
                    .Update(u => u.HasName("UpdateEmployee"))
                    .Delete(d => d.HasName("DeleteEmployee"))
            );
        base.OnModelCreating(modelBuilder);
    }
}

নিচের এই code গুলো দিয়ে stored procedures এর default parameter এর name গুলোও পরিবর্তন করা যায়
public class EmployeeDBContext : DbContext
{
    public DbSet<Employee> Employees { getset; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>().MapToStoredProcedures
            (p => p.Insert(i => i.HasName("InsertEmployee")
                                    .Parameter(n => n.Name, "EmployeeName")
                                    .Parameter(n => n.Gender, "EmployeeGender")
                                    .Parameter(n => n.Salary, "EmployeeSalary"))
                    .Update(u => u.HasName("UpdateEmployee")
                                    .Parameter(n => n.ID, "EmployeeID")
                                    .Parameter(n => n.Name, "EmployeeName")
                                    .Parameter(n => n.Gender, "EmployeeGender")
                                    .Parameter(n => n.Salary, "EmployeeSalary"))
                    .Delete(d => d.HasName("DeleteEmployee")
                                    .Parameter(n => n.ID, "EmployeeID"))
            );
        base.OnModelCreating(modelBuilder);
    }
}

এখন আবার Sample database টা drop করে WebForm1 run করুন। দেখা যাবে parameters এর নাম গুলো আমদের specify করা নাম অনুসারে হয়েছে -
 Entity framework এর code first approach এ default stored procedure গুলোকে overriding করা
Parameters Name of SP


উপরের explanations আরও ভালভাবে বুঝতে এই video টি একবার দেখে আসুন। ধন্যবাদ।।