EntityFramework 学习 一 Update Existing Entity using DBContext in Disconnected Scenario
using System; using System.Collections.Generic; public partial class Student { public Student() { this.Courses = new HashSet<Course>(); } public int StudentID { 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 StudentAddress StudentAddress { get; set; } public virtual ICollection<Course> Courses { get; set; } }
using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Core.Objects; using System.Linq; public partial class SchoolDBEntities : DbContext { public SchoolDBEntities() : base("name=SchoolDBEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Standard> Standards { get; set; } public virtual DbSet<Student> Students { get; set; } public virtual DbSet<StudentAddress> StudentAddresses { get; set; } public virtual DbSet<Teacher> Teachers { get; set; } }
Student stud; //1. Get student from DB using (var ctx = new SchoolDBEntities()) { stud = ctx.Students.Where(s => s.StudentName == "New Student1").FirstOrDefault<Student>(); } //2. change student name in disconnected mode (out of ctx scope) if (stud != null) { stud.StudentName = "Updated Student1"; } //save modified entity using new Context using (var dbCtx = new SchoolDBEntities()) { //3. Mark entity as modified dbCtx.Entry(stud).State = System.Data.Entity.EntityState.Modified; //4. call SaveChanges dbCtx.SaveChanges(); }
1.从DB中获取存在是student
2.在context作用域之外设置studentname
3.使用Context.Entry()方法获取实体的DBEntityEntry,并更改实体状态为modified