Entity Framework Tutorial Basics(24):Update Single Entity
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:
- Get the existing student from DB.
- Change the student name out of Context scope (disconnected mode)
- Pass the modified entity into the Entry method to get its DBEntityEntry object and then mark its state as Modified
- 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的更多相关文章
- Entity Framework Tutorial Basics(25):Delete Single Entity
Delete Entity using DBContext in Disconnected Scenario: We used the Entry() method of DbContext to m ...
- 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 ...
- Entity Framework Tutorial Basics(27):Update Entity Graph
Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...
- Entity Framework Tutorial Basics(20):Persistence in Entity Framework
Persistence in Entity Framework There are two scenarios when persisting an entity using EntityFramew ...
- 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 ...
- 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 ...
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- 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 ...
- Entity Framework Tutorial Basics(19):Change Tracking
Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...
随机推荐
- PhotoShop使用指南(1)——动态图gif的制作
第一步:菜单栏 > 窗口 > 工作区 > 动感 第二步:时间轴 > 设置延迟时间 第三步:时间轴 > 设置循环次数 第四步:存储为Web所用格式 Ctrl+Shift+A ...
- Jmeter基本组件
学习jmeter首先配置环境,使工具运行起来,然后需要了解该工具大致的内容,以下是写的Jmeter基本组件 1.添加线程组:右键点击“测试计划”-->“添加”-->“Threads(Use ...
- UVA - 11014 Make a Crystal (莫比乌斯反演)
给定一个n*n*n的立方体(中心点为原点O),选择尽量多的点,使得对于任意两点A,B,B不在线段OA上. 可以发现,原问题可转化为三维坐标下的点(x,y,z)中有多少个点的gcd(x,y,z)=1. ...
- python沉淀之路~~整型的属性
python的基础知识: 基本数据类型:int str list tuple dict bool 一.整型的属性功能 1.工厂方法将字符串转换成整型 a = " b = ...
- 【redis】redis的 key的命名规则
key的命名规则 定义为 MS-TEN:SESSION_KEY_IN_LOGIN_NAME:fqh 使用:进行分割,这样存入redis的是有层次结构的,如下
- DCOS安装
安装pre-flight master机器会安装上安装文件(同时check条件是否满足要求),其他的agent设备只是check各种条件是否具备. 确保53/2181端口没有被占用:centos7每次 ...
- 蓝桥杯 算法训练 ALGO-118 连续正整数的和
算法训练 连续正整数的和 时间限制:1.0s 内存限制:256.0MB 问题描述 78这个数可以表示为连续正整数的和,1+2+3,18+19+20+21,25+26+27. 输入一个正整数 n ...
- 转:InnoDB Log Block Structure(InnoDB日志Block结构详解)
文章转载自等博 InnoDB Log Block Structure(InnoDB日志Block结构详解)
- “百度杯”CTF比赛 九月场
Test: 题目提示查资料 打开地址,是一个海洋cms 海洋cms有个前台getshell的漏洞 在地址后加上/search.php?searchtype=5&tid=&area=ev ...
- struts1-mapping.getInputForward()与mapping.getInput
转自:https://www.cnblogs.com/azai/archive/2010/06/05/1752416.html 奇怪为什么登陆失败的时候 没有错误提示.这个问题困扰了N久 仔细看了下, ...