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. 1113. Integer Set Partition (25)

    Given a set of N (> 1) positive integers, you are supposed to partition them into two disjoint se ...

  2. curl获取图片

    <?php set_time_limit(0); //执行30秒超时后继续执行 header("Content-type:text/html;charset=utf-8"); ...

  3. Maven里头的pom.xml配置详解

    正常的pom配置文件如下所示: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...

  4. UFLDL新版教程

    http://ufldl.stanford.edu/tutorial/ 还带编程作业.

  5. PHP根据两点间的经纬度计算距离,php两点经纬度计算(转)

    这是一个不错的示例,直接贴代码,首先要知道纬度值.经度值 /** * @desc 根据两点间的经纬度计算距离 * @param float $lat 纬度值 * @param float $lng 经 ...

  6. CentOS6.5下安装mongodb

    MongoDB是目前最常用的NoSQL-非关系型数据库. 本文将介绍在CentOS下如何通过yum安装MongoDB. 1.首先在CentOS6.5下,编辑Mongo的yum源: 在/etc/yum. ...

  7. Mongodb 副本集的节点详细操作

    副本集操作 官方文档:https://docs.mongodb.com/v3.2/reference/method/js-replication/ 1 rs.add(){ _id: <int&g ...

  8. maven 学习 十 关于打包

    clean package -Dmaven.test.skip=true -P product 这个命令干的活: 清class文件,打包构建,跳过测试,注意最后一个 -P product, 会激活项目 ...

  9. python jvm数据

    在网上找的抱歉忘了原链接了额 #!/usr/bin/env python # # import os import commands import re import sys (status1, re ...

  10. docker 笔记 (5)常用命令

    images    显示镜像列表 history   显示镜像构建历史 commit    从容器创建新镜像 build     从 Dockerfile 构建镜像 tag       给镜像打 ta ...