Introduction
This article shows how to perform Entity Splitting and later we will also look at how to perform a select data operation using the Code First Approach.
Create console application
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_CodeFirstApproach
- {
- 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_CodeFirstApproach
- {
- 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_CodeFirstApproach
- {
- class Program
- {
- static void Main(string[] args)
- {
- EmployeeContext empContext = new EmployeeContext();
- var query = from r in empContext.Employees select r;
-
- foreach (var r in query)
- {
- Console.WriteLine("FirstName: " + r.FirstName + " LastName: " + r.LastName + " Phone: " + r.Phone + " Email: " + r.Email);
- }
- Console.ReadKey();
-
- }
- }
- }
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 select data operation using the Code First Approach. Happy coding!