Entity Framework - SPLessons

Entity Framework Updation of Single Entity

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

Entity Framework Updation of Single Entity

Entity Framework Update of Single Entity

shape Description

If following Database first approach, then one have to create Entity Model otherwise create entities and context class.

Entity for the employee

shape Example

[csharp]using System; using System.Collections.Generic; public partial class Employee { public Employee() { this.Department = new HashSet<Department>(); } public int EmployeeID { get; set; } public string EmployeeName { get; set; } public Nullable<int> StandardId { get; set; } public virtual Standard Standard { get; set; } public virtual Address EmployeeAddress { get; set; } public virtual ICollection<Department> Departments { get; set; } } [/csharp]

Context class

shape 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") { } public virtual DbSet<Department> Departments{ get; set; } public virtual DbSet<Standard> Standards { get; set; } public virtual DbSet<Employee> Employees{ get; set; } public virtual DbSet<EmployeeAddress> EmployeeAddresss{ get; set; } public virtual DbSet<Name> Names{ get; set; } } [/csharp]

Updation of Entity

shape Code

[csharp] Student stud; //Get Employee from DB using (var con= new EmployeeDBEntities()) { emp = con.Employee.Where(e => e.EmployeeName == "New Employee1").FirstOrDefault<Employee>(); } //2. change Employee name in disconnected mode (out of conscope) if (emp!= null) { emp.EmployeeName = "Updated Employee1"; } //save modified entity using new Context using (var dbCon = new EmployeeDBEntities()) { //3. Mark entity as modified dbCon.Entry(emo).State = System.Data.Entity.EntityState.Modified; //4. call SaveChanges dbCon.SaveChanges(); } [/csharp]