Wednesday 18 February 2015

Entity Splitting in EntityFramework

Entity Splitting Means Split this entity into multiple database table when they have same columnname(common key).
We will understand this with an example
Step(1): Create Two table
First of all we will create two table those have same column name with values. 
In my case there are 2 table “Students” and “StudentsDetail”

Run below script in your SQL SERVER this will create two tables

Create table Students
(
     StudentID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50)
)
GO

Create table StudentContactDetails
(
     StudentID int primary key,
     Email nvarchar(50),
     Mobile nvarchar(50)
)
GO

Insert into Students values ('Munesh', 'Sharma', 'Male')
Insert into Students values ('Rahul', 'Sharma', 'Male')
Insert into Students values ('Sara', 'vilium', 'Female')
Insert into Students values ('Mark', 'hash', 'Female')
Insert into Students values ('ABC', 'EFG', 'Male')

Insert into StudentContactDetails values
(1, 'Munesh@abc.com', '111111111')
Insert into StudentContactDetails values
(2, 'Rahul@abc.com', '2222222222')
Insert into StudentContactDetails values
(3, 'Sara@abc.com', '3333333333')
Insert into StudentContactDetails values
(4, 'Mark@abc.com', '44444444444')
Insert into EmployeeContactDetails values
(5, 'ABC@abc.com', '5555555555')












Step(2): Add tables to entity
Now go to your application and Right click on solution explorer and add a “ADO.Net Entity Data Modal” and select  database first approach.

After that click on next and select database connection and select database name and then click on next and select your tables which you created now, And click FINISH


When you click on FINISH you will see “Student” and “StudentContactDetail”  Entities

Step(3): Mapping entity
There is One to one mapping b/w entity , here we have two entity . Now we want to single “StudentInfo”  To map both “Student” and “StudentContactDeatil” Entities.
To Achieve this there are some steps
1.   Cut Email, Mobile properties from StudentContactDetail entity and paste in Student entity
2.   Delete StudentContactDetail entity. When you will click on Delete you will see a screen   "Delete Unmapped Tables and Views"  there you  click NO.
3.   After that your Entity will be like that

4.   Right click on Student  entity and select "Table Mapping"  option from the context menu. Map StudentId, Email, Mobile  properties to the respective columns of StudentContactDetails table. 




Step(4): With an example
we have only one Entity, now Build the solution. Add a WebForm by right click on solution explorer and add these following 3 controls from toolBox.
GridView,  DetailsView, EntityDataSource

a). Go to the  "Show Smart Tag" option of EntityDataSource control. And click on Configure Data Source link

b) Select your connection name (in my case it is “Entitysplitting”) from the Named Connection dropdownlist and click Next

c) Select Student from EntitySetName dropdownlist and enable Inserts, Updates and Deletes Checkboxes.

Set  GridView control properties

a). Go to the "Show Smart Tag" option of gridview.
b) Select "EntityDataSource1" from "Choose Data Source" dropdownlist
c) Select Enable Editing and Enable Deleting checkboxes

Set  DetailsView control properties

a)  go to the "Show Smart Tag" option of DetailsView .
b) Select "EntityDataSource1" from "Choose Data Source" dropdownlist
c) check (select) Enable Inserting checkbox
d) Set DeafultMode = Insert. Use properties window to set this.
e) Set InsertVisible="false" for the StudentID BoundField. This can be done through  HTML Source code.
f) Generate ItemInserted event handler method for DetailsView control , And write this code
protected void DetailsViewEntity_ItemInserted(object sender
DetailsViewInsertedEventArgse)
{
       GridView1.DataBind();

}



now run the application. And perform these operation Insert, update , delete  and notice that both the tables (Students and Students  ContactDetails) are updated. 


Sunday 15 February 2015

Code-First Stored Procedure Entity Framework

We can perform CURD operation in Code First approach using stored procedure.
Step(1): For creating Code First model using Stored Procedure we have to  override the OnModelCreating method of DBContext .
We have to add this code
protected override void OnModelCreating(DbModelBuilder Builder)  
{  
    Builder.Entity<yourEntity>().MapToStoredProcedures(your Link query);  


The MapToStoreProcedures method has two type of overloaded methods, First one is without a parameter. This method uses the Code-First Entity framework method for  the Stored Procedure. The second  method takes parameters  as an input and  we can customize Stored Procedure name, parameters, and so on.
We will understand this with an example
Step(2): Add a  2 class for  “ Department.cs”  and  “Student.cs”  after that  give the parameters name
Department.cs” class is like that
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstStoredProcedureEntityFramework
{
    public class Department
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int DepartmentId { get; set; }
        public string Subject { get; set; }
        public List< Student > Students{ get; set; }
    }
}

Student.cs” class is like that
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstStoredProcedureEntityFramework
{
    public class Student
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public int DepartmentId { get; set; }
        public Department Department { get; set; }
    }
}

Step(3):   Now Add a  “Context” class, In this class we will use OnModelCreating method for  mapping with StoredProcedure and “Student” Entity.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstStoredProcedureEntityFramework
{

    public class StoredProcedureEntitiesContext : DbContext
    {
        public StoredProcedureEntitiesContext()
            : base("name=Entities")
        {
            Database.Log = Console.WriteLine;
        }
        public DbSet<Department> Departments { get; set; }
        public DbSet< Student > Students { get; set; }

        protected override void OnModelCreating(DbModelBuilder Builder)
        {
            Builder.Entity< Student >()
                .MapToStoredProcedures(s => s.Insert(u => u.HasName("Insert StudentDetail ", "dbo"))
                                                .Update(u => u.HasName("Update StudentDetail ", "dbo"))
                                                .Delete(u => u.HasName("Delete StudentDetail ", "dbo"))
                );
        }
    }
}

Step(3):   Enable Migration
1.   Tools -> Nuget Package manager -> package manager consol

In console screen write this
enable-migrations -ContextTypeName CodeFirstStoredProcedure.EntitiesContext -MigrationsDirectory:EntitiesMigrations


After this Add Migration Configuration..
->
write this below command  in console screen
Add-Migration -configuration CodeFirstStoredProcedure.EntitiesMigrations.Configuration InitialEntities

Purpose for Adding Migration command..
We add migration command because its generates the Dbmigration class , and this Dbmigration class has the definition of All the stored procedure.

Step(4):   Add a class For writing stored procedure

namespace CodeFirstStoredProcedureEntityFramework.EntitiesMigrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class StoredProcedure : DbMigration
    {
        public override void Up()
        {
            CreateStoredProcedure(
                "dbo.InsertStudentInfo",
                p => new
                    {
                       
                        StudentName = p.String(),
                        DepartmentId = p.Int(),
                    },
                body:
                    @"INSERT [dbo].[StudentInfo]([StudentName], [DepartmentId])
            VALUES (@Name, @DepartmentId)
                     
            DECLARE @StudentId int
            SELECT @StudentId = [StudentId]
            FROM [dbo].[StudentInfo]
            WHERE @@ROWCOUNT > 0 AND [StudentId] = scope_identity()
                     
            SELECT t0.[StudentId]
            FROM [dbo].[StudentInfo] AS t0
            WHERE @@ROWCOUNT > 0 AND t0.[StudentId] = @StudentId"
            );

            CreateStoredProcedure(
                "dbo.UpdateStudentInfo",
                p => new
                    {
                        StudentId = p.Int(),                      
                        StudentName = p.String(),
                        DepartmentId = p.Int(),
                    },
                body:
                    @"UPDATE [dbo].[StudentInfo]
            SET [StudentName] = @StudentName, [DepartmentId] = @DepartmentId
            WHERE ([StudentId] = @StudentId)"
            );

            CreateStoredProcedure(
                "dbo.DeleteStudentInfo",
                p => new
                    {
                        StudentId = p.Int(),
                    },
                body:
                    @"DELETE [dbo].[StudentInfo]
            WHERE ([StudentId] = @StudentId)"
            );

        }

        public override void Down()
        {
            DropStoredProcedure("dbo.DeleteStudentInfo");
            DropStoredProcedure("dbo.UpdateStudentInfo");
            DropStoredProcedure("dbo.InsertStudentInfo");
        }
    }
}


Step(5):   Update Database

Update-Database -configuration:CodeFirstStoredProcedure.EntitiesMigrations.Configuration -Verbose
Step(6):   After Executing this stored procedure.
When you will execute this Stored procedure this will create 3 stored procedure and the definition will be like this.
CREATE PROCEDURE [dbo].[InsertStudentinfo]     
    @Name [nvarchar](max), 
    @DepartmentId [int] 
AS 
BEGIN 
    INSERT [dbo].Studentinfo([StudentName], [DepartmentId]) 
    VALUES (@StudentName, @DepartmentId) 
     
    DECLARE @StudentId int 
    SELECT @StudentId = [@StudentId] 
    FROM [dbo].Studentinfo 
    WHERE @@ROWCOUNT > 0 AND [@StudentId] = scope_identity() 
     
    SELECT t0.[@StudentId] 
    FROM [dbo].Studentinfo AS t0 
    WHERE @@ROWCOUNT > 0 AND t0.[@StudentId] = @@StudentId 
END 
 
GO 
 
CREATE PROCEDURE [dbo].[UpdateStudentinfo] 
    @StudentId [int],  
    @StudentName [nvarchar](max), 
    @DepartmentId [int] 
AS 
BEGIN 
    UPDATE [dbo].Studentinfo 
    SET [Code] = [Name] = @StudentName, [StudentId] = @StudentId 
    WHERE ([StudentId] = @StudentId) 
END 
 
GO 
 
CREATE PROCEDURE [dbo].[DeleteStudentinfo] 
    @StudentId [int] 
AS 
BEGIN 
    DELETE [dbo].[StudentInfo] 
    WHERE ([StudentId] = @StudentId) 
END




Step(7):   Insert Record from code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeFirstStoredProcedureEntityFramework
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EntitiesContext context = new EntitiesContext())
            {
                Studentinfo Detail = new Student();

                Detail.Name = "Munesh Sharma";
                Detail.StudentId = 1;
                context.Student.Add(Detail);
                context.SaveChanges();
                Console.ReadLine();
            }
        }
    }
}

When you will run your application it will update a record in database.






C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...