Entity Framework - SPLessons

Entity Framework Insertion of Single Entity

Home > Lesson > Chapter 13
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Entity Framework Insertion of Single Entity

Entity Framework Insertion of Single Entity

shape Description

After creation Entity Data Model if want to insert a new entity, then follow the below steps.

Create an Employee Entity 

shape Example

Write the following code to create anEntity [csharp] using System; using System.Collections.Generic; public partial class Employee { public Employee() { this.Departments = new HashSet<Department>(); } public int EMployeeId { get; set; } public string StudentName { get; set; } public Nullable<int> StandardId { get; set; } public byte[] RowVersion { get; set; } public virtual Standard Standard { get; set; } public virtual Salary Salary { get; set; } public virtual ICollection<Department> Departments { get; set; } } [/csharp]

Context Class

shape Example

See the following code [csharp] using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Core.Objects; using System.Linq; public partial class EmployeeDBEntities : DbContext { public EmployeeDBEntities () : base("name=EmployeeDBEntities ") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public virtual DbSet<Department> Departments{ get; set; } public virtual DbSet<Standard> Standards { get; set; } public virtual DbSet<Employee> Employees{ get; set; } public virtual DbSet<Salary> Salary{ get; set; } public virtual DbSet<Name> Name { get; set; } } [/csharp] See the following to know "How to save the single entity". [csharp] class Program { static void Main(string[] args) { // create new Employee entity object in disconnected scenario var newEmp = new Employee(); //set Employee name newEmp.Name = "Bill"; //create DBContext object using (var con = new EmployeeDBEntities()) { //Add Employee object into Employee DBset con.Employees.Add(newEmp); // call SaveChanges method to save employee into database con.SaveChanges(); } } } [/csharp]