Introduction
This article shows how to perform Entity Splitting and later we will also look at how to perform an insert data operation using the Code First Approach.
Create a 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_Insert
- {
- 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_Insert
- {
- 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_Insert
- {
- public class Program
- {
- static void Main(string[] args)
- {
- EmployeeContext empContext = new EmployeeContext();
- Employee emp = new Employee()
- {
- FirstName = "Haney",
- LastName = "Jow",
- Phone = 12345678,
- Email="[email protected]"
-
- };
- empContext.Employees.Add(emp);
- empContext.SaveChanges();
- Console.WriteLine("Inserted");
- 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 an insert data operation using the Code First Approach. Happy coding!