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. 树莓派视频监控 —— 使用 mjpg

    下载到树莓派本地: $ wget https://github.com/jacksonliam/mjpg-streamer/archive/master.zip $ unzip master.zip ...

  2. ICE的连接机制

    1.当使用ICE的proxy进行方法调用时,ICE运行环境会建立一个到服务器的连接.当proxy提供了多个endpoint时   默认的ICE运行环境选择endpoint的行为为random,可以通过 ...

  3. 【剑指offer】以o(1)复杂度删除啊链表的节点,C++实现(链表)

    0.简介       本文是牛客网<剑指offer>刷题笔记. 1.题目       在O(1)时间内删除链表节点. 2.思路         前提条件:删除的节点在链表上:边界条件:链表 ...

  4. SQL夯实基础(二):连接操作中使用on与where筛选的差异

    一.on筛选和where筛选 在连接查询语法中,另人迷惑首当其冲的就要属on筛选和where筛选的区别了,如果在我们编写查询的时候, 筛选条件的放置不管是在on后面还是where后面, 查出来的结果总 ...

  5. Python List reverse()方法

    reverse() 函数用于反向列表中元素,参数 NA,该方法没有返回值,但是会对列表的元素进行反向排序,原来的列表被改变,生成新的列表. 例子:list1 = ['Google', 'Runoob' ...

  6. “makefile”写法详解,一步一步写一个实用的makefile,详解 sed 's,$∗\.o[ :]*,\1.o $@ : ,g' < $@.

    目的:编写一个实用的makefile,能自动编译当前目录下所有.c/.cpp源文件,支持二者混合编译.并且当某个.c/.cpp..h或依赖的源文件被修改后,仅重编涉及到的源文件,未涉及的不编译. 二要 ...

  7. DotNetBar笔记

    1.TextBoxDropDown  这是一个绝对TMD坑爹的狗屁玩意儿.键盘的四个事件全部不好使.但是这个玩意儿有个好处就是他的DropDownControl属性可以用来制作ComboGrid. 然 ...

  8. linux指令 apt-grt指令使用

    apt-get 是linux的一条指令,主流的linux版本Debian和ubuntu都使用apt-get来安装软件.那么,需安装的软件都放在哪里呢??? apt-get 利用软件安装源来安装软件,其 ...

  9. Mysql 5.6 MHA (gtid) on Kylin

    mha on Kylinip hostname repl role mha role192.168.19.69 mysql1 master node192.168.19.73 mysql2 slave ...

  10. 从CoreAnimation到Pop

    pop是Facebook在开源的一款动画引擎,看下其官方的介绍: Pop是一款在iOS.tvOS和OS X平台通用的可扩展动画引擎.它在基本静态动画的基础上,增加了弹性以及衰减动画,这在创建真实有物里 ...