Introduction
This article shows how to perform Entity Splitting and later we will also look at how to perform a update data operation using the Code First Approach.
Create console application as in the following:
Employee.cs
- 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 EntitySplitting_CFA_Update
- {
- public class Employee
- {
- public Employee()
- {
- }
-
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int Id { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public int Phone { get; set; }
- public string Email { get; set; }
- }
- }
Employeecontext.cs
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace EntitySplitting_CFA_Update
- {
- public class EmployeeContext : DbContext
- {
- public EmployeeContext()
- : base("EmployeeConn")
- {
- Database.SetInitializer<EmployeeContext>(new CreateDatabaseIfNotExists<EmployeeContext>());
- }
-
- public DbSet<Employee> Employees { get; set; }
-
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<Employee>()
- .Map(map =>
- {
- map.Properties(r => new
- {
- r.Id,
- r.FirstName,
- r.LastName
- }); map.ToTable("Employee");
- })
- .Map(map =>
- {
- map.Properties(r => new
- {
- r.Phone,
- r.Email
- }); map.ToTable("EmployeeDetails");
- });
-
- base.OnModelCreating(modelBuilder);
- }
- }
- }
Web.config
- <connectionStrings>
- <add name="EmployeeConn"
- connectionString="Data Source=WIN-B4KJ8JI75VF;Initial Catalog=EmployeeDB;Integrated Security=true"
- providerName="System.Data.SqlClient"/>
- </connectionStrings>
Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace EntitySplitting_CFA_Update
- {
- class Program
- {
- static void Main(string[] args)
- {
- EmployeeContext empContext = new EmployeeContext();
- int empId = 1;
- var emp = empContext.Employees.Where(a => a.Id.Equals(empId)).SingleOrDefault();
- emp.FirstName = "Jonny";
- emp.Phone = 01234;
- empContext.SaveChanges();
- }
- }
- }
The output of the application looks as in the following:
Summary
In this article we saw how to perform Entity Splitting and how to perform a update data operation using the Code First Approach. Happy coding!