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 ...
随机推荐
- SQL-表的操作(创建表,删除表,更改列,插入新行,更改行的值,删除表中数据)
一,操作表及列 1.创建表: CREATE TABLE test (ID int PRIMARY KEY IDENTITY,Name varchar(20) ) 2.删除表 DROP TABLE t ...
- url参数的编码解码Demo
为了保证在页面传递数据的安全性,我们通常会对Url传递的参数进行编码解码操作.我们写一个Demo剖析URL编码解码过程. 完整Demo下载地址 1. Url参数如何在服务端进行编码和解码. 1.1 U ...
- Agc001_D Arrays and Palindrome
传送门 题目大意 给定一个元素和为$N$的有$M$个数的序列$A$,请你可以$A$元素排列的顺序,并需要构造一个有$K$个($K$可以自己定)数的数列,使得任意一个长度为$N$的字符串,若满足:前$A ...
- poj1463 Strategic game[树形DP]
求一棵树每条边都被选上的点覆盖掉的最少选点数. 一条边被覆盖掉,必须他父亲和儿子中选一个..这不就是比NOIP2018D2T3还裸的暴力么.水掉. lyd给的练习题都什么**玩意儿.. code不挂了 ...
- axios 请求报错
报错如下: 解决:axios的请求配置中的baseURL配置错误,修改好即可. 报错前: baseURL: "192.168.30.220:3000", 解决后:baseURL: ...
- nginx 400
做服务器nginx配置的时候有出现过 400 Bad Request 服务器无法理解请求的格式,客户端不应当尝试再次使用相同的内容发起请求.
- MLCC 电容的的 NP0 C0G 材质
MLCC 电容的的 NP0 C0G 材质 随手记一下. MLCC 中最稳定的材质 NP0 C0G,NP0 和 C0G 是相同的,只是不同的产商不同的名字而已. 注意中间的是 0 不是 英文字母 O,虽 ...
- bzoj 3907 网格 bzoj2822 [AHOI2012]树屋阶梯——卡特兰数(阶乘高精度模板)
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3907 https://www.lydsy.com/JudgeOnline/problem.p ...
- Poj 2421 Constructing Roads(Prim 最小生成树)
题意:有几个村庄,要修最短的路,使得这几个村庄连通.但是现在已经有了几条路,求在已有路径上还要修至少多长的路. 分析:用Prim求最小生成树,将已有路径的长度置为0,由于0是最小的长度,所以一定会被P ...
- (转)SC Create 创建一个Windows系统服务
本文转载自:http://blog.sina.com.cn/s/blog_62b8fc330100l9px.html C:\Users\sophiaX>sc 描述: SC 是用于与服务控制管理器 ...