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 ...
随机推荐
- awk指令的使用
awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大 awk工作流程是这样的:读入有'\n'换行符分割的一条记录,然后将记录按指定的域分隔 ...
- Qt之事件处理机制
思维导读 一.事件简介 QT程序是事件驱动的, 程序的每个动作都是由内部某个事件所触发.QT事件的发生和处理成为程序运行的主线,存在于程序整个生命周期. 常见的QT事件类型如下: 键盘事件: 按键按下 ...
- LeetCode Relative Ranks
原题链接在这里:https://leetcode.com/problems/relative-ranks/#/description 题目: Given scores of N athletes, f ...
- BZOJ4861 [Beijing2017]魔法咒语
题意 Chandra 是一个魔法天才.从一岁时接受火之教会洗礼之后, Chandra 就显示出对火元素无与伦比的亲和力,轻而易举地学会种种晦涩难解的法术.这也多亏 Chandra 有着常人难以企及的语 ...
- C# partial 说明(转)
http://www.cnblogs.com/Echo_saq/archive/2012/11/19/2777058.html 1. 什么是局部类型? C# 2.0 引入了局部类型的概念.局部类型允许 ...
- python之 centos6.7下 python 3.5.2 源码、Django-1.9 安装
在linux6.5中已经自带了python 2 .python 2.6 ,并且yum程序使用的就是自带的python,所以系统自带的python不要随意卸载否则可能导致yum用不了. 测试环境:cen ...
- gulp之文件合并以及整合html中的script和link
gulp的文件合并,也就是将多个js或css文件合并为一个的插件是:gulp-concat gulp将html中的多个<script>或<link>合并为一个的插件是:gulp ...
- spring事务-说说Propagation及其实现原理
前言 spring目前已是java开发的一个事实标准,这得益于它的便利.功能齐全.容易上手等特性.在开发过程当中,操作DB是非常常见的操作,而涉及到db,就会涉及到事务.事务在平时的开发过程当中,就算 ...
- 聊聊“现在学习MFC有用吗?”
我用MFC做了4年多,后来转到WPF也做了快5年.对于二者,不敢说精通,但应该算入门.结合自己经历,如果不考虑项目需求,我认为新手学习WPF或许更好点.有3点: 1)大家都知道最近几年Motorola ...
- [转载]TSO、UFO、GSO、LRO、GRO和RSS介绍
TSO.UFO.GSO.LRO.GRO和RSS介绍 ethtool -k < 网络接口>,ethtool --show-offload < 网络接口>,或者可以看到很多网络接口 ...