Update Existing Entity using DBContext in Disconnected Scenario:

In this chapter, you will learn how to update a single entity in a disconnected scenario.

If you use Database-First approach, then create an Entity Data Model as shown in the previous chapter for SchoolDB sample database. Or, if you use Code-First or Model-First approach, then create entities and context classes. In any case, entities and context classes will look similar.

Here, we will see how to update a single Student entity (not entity graph). The following is a Student entity.

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; }
}

The following is a context class.

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; }
}

The following example shows how to update a Student entity in the disconnected scenario:

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();
}

As you see in the above code snippet, we are doing the following steps:

  1. Get the existing student from DB.
  2. Change the student name out of Context scope (disconnected mode)
  3. Pass the modified entity into the Entry method to get its DBEntityEntry object and then mark its state as Modified
  4. Call SaveChanges() method to update student information into the database.

SaveChanges will send the following update query to the database:

exec sp_executesql N'update [dbo].[Student]
set [StudentName] = @0, [StandardId] = @1
where ([StudentID] = @2)',N'@0 varchar(50),
@1 int,@2 int',@0='Updated Student1',@1=299,@2=267

In this way, we can easily update a single entity using DBContext in the disconnected mode.

DbContext.Entry method returns an instance of DBEntityEntry for a specified Entity. An instance of DbEntityEntry class providea access to information about a given entity and its state. You can change the state of an entity to Added, Updated, or Deleted.

In the next chapter you will learn how to delete a single entity in the disconnected mode.

Entity Framework Tutorial Basics(24):Update Single Entity的更多相关文章

  1. Entity Framework Tutorial Basics(25):Delete Single Entity

    Delete Entity using DBContext in Disconnected Scenario: We used the Entry() method of DbContext to m ...

  2. Entity Framework Tutorial Basics(23):Add Single Entity

    Add New Entity using DBContext in Disconnected Scenario: In this chapter you will learn how to add n ...

  3. Entity Framework Tutorial Basics(27):Update Entity Graph

    Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...

  4. Entity Framework Tutorial Basics(20):Persistence in Entity Framework

    Persistence in Entity Framework There are two scenarios when persisting an entity using EntityFramew ...

  5. Entity Framework Tutorial Basics(8):Types of Entity in Entity Framework

    Types of Entity in Entity Framework: We created EDM for existing database in the previous section. A ...

  6. Entity Framework Tutorial Basics(2):What is Entity Framework?

    What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monoton ...

  7. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  8. Entity Framework Tutorial Basics(31):Migration from EF 4.X

    Migration from Entity Framework 4.1/4.3 to Entity Framework 5.0/6.0 To migrate your existing Entity ...

  9. Entity Framework Tutorial Basics(19):Change Tracking

    Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...

随机推荐

  1. cscope配置和使用

    , cscope安装 软件下载:http://sourceforge.net/project/showfiles.php?group_id=4664 软件安装: ./configure --with- ...

  2. dirent.h

    #include <dirent.h> 是POSIX.1标准定义的unix类目录操作的头文件,包含了许多UNIX系统服务的函数原型,例如opendir函数.readdir函数. opend ...

  3. mybatis与oracle使用总结

    Oracle使用总结 1.新建表删除表 新建表语句: CREATE TABLE +表名{ } create table AFA_USER ( USER_ID VARCHAR2() not null, ...

  4. 聊聊WPF中的Dispatcher

    DispatcherObject,Dispatcher,Thread之间的关系 我们都知道WPF中的控件类都是从System.Windows.Threading.DispatcherObject继承而 ...

  5. Pix mesa 自动化测试

    最近在准备PIX的认证, 需要进行mesa测试. 但是Mesa的标准测试工具中没有针对PIX的TestCase, 只是提到NIST的web测试.路径为:http://pixpdqtests.nist. ...

  6. 使用Azure Site Recovery把VM批量搬迁到Azure

    Azure Site Recovery可以提供如下服务: Site Recovery 服务:Site Recovery 可以在站点出现故障时,让应用在其他站点继续可用,从而确保业务连续性. Site ...

  7. linux 内存释放命令

    我使用的是CentOS 6.5 ,由于卸载Solr 后发现内存占用挺多的,我想释放一下内存,就查阅了一些资料,分享给大家: 1.free -m  查看内存的使用情况,-m表示单位是兆 2.echo 1 ...

  8. [C++] 贪心算法之活动安排、背包问题

    一.贪心算法的基本思想 在求解过程中,依据某种贪心标准,从问题的初始状态出发,直接去求每一步的最优解,通过若干次的贪心选择,最终得出整个问题的最优解. 从贪心算法的定义可以看出,贪心算法不是从整体上考 ...

  9. java代码继承。。。找出不能继承父类方法的问题

    总结:当子类中没有定义name属性时,在子类的无参构造方法中,父类的姓名是不能被继承的. 输出的结果是,子类无参构造方法里的属性值,也就是是属 控制台显示: 我叫:周杰伦,今年:2岁我的姓名:周杰伦, ...

  10. Java-API:java.util.list

    ylbtech-Java-API:java.util.list 1.返回顶部   2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部 1. https://docs.oracle.co ...