Friday 6 March 2015

Entity splitting with code first approach in entity framework

I explained before that Entity Splitting Means Mapping an entity or change two table into one table when they have same columnname(common key).
We will understand this with an example
Step(1): Create a new web Project
Go to the visual studio and then file and select new Website after that select new Empty web application and give the name for this.
 Step(2) : Add a class
Add a class and give the name for this as “ student.cs”, And write the following  code.
namespace Demo
{
    public class Student
    {
        // These property values will store in Student  Table
        public int StudentId { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
        public string Gender { getset; }


// These property values will store in StudentContactDetails Table
public string Email { getset; }
public string Mobile { getset; }
    }
}



 Step(3) : Add a another  new class
Add a new class and give the name for this like “StudentDBContext.cs” and write this code.
using System.Data.Entity;
namespace Demo
{
    public class StudentDBContextDbContext
    {
        public DbSet<Student> Students { getset; }
    }
}


Step(4) : Add a new class to the project
Add a new to the project for performing operations, And give the name for  this as “StudentDetails.cs”. and write this code
using System.Collections.Generic;
using System.Linq;
namespace Demo
{
    public class StudentDetails
    {
   StudentDBContext  _ studentDBContext  = new StudentDBContext  ();

        public List<Student> GetStudent()
        {
            return  _studentDBContext .Student.ToList();
        }

        public void InsertStudentinfo(Student  _student)
        {
            _ studentDBContext .Student.Add(_student);
            _ studentDBContext .SaveChanges();
        }

        public void UpdateStudentinfo(Student  _student)
        {
            Students  _student ToUpdate = _studentDBContext.Student
                .SingleOrDefault(x => x.StudentId == _student.StudentId);

            _studentToUpdate .StudentId = _student.StudentId;
            _studentToUpdate .FirstName = _student.FirstName;
            _studentToUpdate .Gender = _student.Gender;
            _studentToUpdate .Email = _student.Email;
            _studentToUpdate .Mobile = _student.Mobile;
            

            _studentDBContext.SaveChanges();
        }

        public void DeleteStudentinfo(Student  _student)
        {
            Student  _ studentToDelete = _studentDBContext.Students
                .SingleOrDefault(x => x.StudentId == _student.StudentId);
            _studentDBContext. Students.Remove(_studentToDelete);
            _ studentDBContext.SaveChanges();
        }
    }
}


Step(5) : Establish Database connection
Now to Web.config file and establish database connection in connection string tag.
<connectionStrings>
  <add name="StudentDBContext"
        connectionString="server=.; database=EntitySplitting; integrated security=SSPI;"
        providerName="System.Data.SqlClient" />
</connectionStrings>


Step(6) : Operation on gridview
Add a WebForm by right click on solution explorer and add these following 3 controls from toolBox.
GridView,  DetailsView, ObjectDataSource
a). Go to the  "Show Smart Tag" option of ObjectDataSource control. And click on Configure Data Source link, When you will click on this link you will see a “business object form” here you select your business object from dropdown in my case it is “ StudentDetails”. And click on next.



(B) : After click on next you will see a screen for “define data Modal” here you give the Methods for Delete ,insert and update.


(C) : After this go to “ smart tag of gridview” and choose datasource as “Object dataSource” and check “ enable editing” and “enable deleting”  checkboxes .


(D): Go to the properties of gridview and  give “StudentID” in DataKeyName  property.
(E): click on “smart tag of Detailview and select datasource and check enable inserting. And go to properties and put “default mode” as insert

(F) now go to event of “detailview” and click on “item inserted” event and write this code.
protected void DetailsView1_ItemInserted(object senderDetailsViewInsertedEventArgse)
{
    GridView1.DataBind();
}



(G). Run the application , and at this time  entity framework Creates one Table i.e Student table. But we want that EF  to create the 2 tables.
a) Students  table which have column  StudentId, FirstName, LastName and Gender
b) StudentContactDetails table which have column   StudentId, Email, Mobile .
(H).  Go to “StudentDBContext.cs” class and override OnModelCreating() to make two different tables for getting this approach write this below code.
OnModelCreating() method is a virtual method present in DbContext class.
public class StudentDBContext : DbContext
{
    public DbSet<Student> Students { getset; }

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

            map.ToTable("Students");
        })
        // Specify properties to map to StudentContactDetails table
        .Map(map =>
        {
            map.Properties(p => new
            {
                p. StudentId,
                p.Email,
                p.Mobile,
            });

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

        base.OnModelCreating(modelBuilder);
    }
}


(i). Go to SQL server and delete previous database table which contain only one table .
(J): Run your application and now you will see database with two tables. As Student and StudentContactDetails.







 Now you can do any operation from "update" Delete, and Insert ,these two tables will update properly.

No comments:

Post a Comment

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...