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 ...
随机推荐
- BEC listen and translation exercise 12
More than 220 cities now have air quality monitoring systems and 42 others will have systems in plac ...
- spring学习-4
bean的作用域 使用bean的scope属性来配置bean的作用域 scope="singleton":默认是单例模式即容器初始化创建bean实例,在整个容器的生命周期内只创建这 ...
- MonoBehavior lifecycle
awake 只调用一次, awake在所有obj都初始化之后被调用. 用途: 初始化游戏状态 设置脚本间的引用 ### ExecuteInEditMode 编辑模式下 ``` 这个模式下,脚本编译,会 ...
- C语言中time函数获取系统时间
可以通过time()函数来获得计算机系统当前的日历时间(Calendar Time),处理日期时间的函数都是以本函数的返回值为基础进行运算.其原型为: time_t time(time_t * t); ...
- UVA - 10723 Alibaba (dp)
给你两个长度不超过30的字符串序列,让你找到一个最短的字符串,使得给定的两个字符串均是它的子序列(不一定连续),求出最短长度以及符合条件的解的个数. 定义状态(a,b,c)为当前字符串长度为a,其中包 ...
- BZOJ - 2142 礼物 (扩展Lucas定理)
扩展Lucas定理模板题(貌似这玩意也只能出模板题了吧~~本菜鸡见识鄙薄,有待指正) 原理: https://blog.csdn.net/hqddm1253679098/article/details ...
- 一道SQL的面试题之联想
一道SQL的面试题之联想 本人工作在一家小型的民营企业,主要从事业务系统的日常维护,二次开发,菜鸟一枚.周五经理准备面试两个开发人员,据简历,都还比较不错,让经理产生了想法,于是准备了一套面试题目,给 ...
- 1、在Eclipse中安装TestNG(离线方式)
1.TestNG安装包:链接: https://pan.baidu.com/s/1UXZlJfrp8LM-6XmDLzVXKg 密码: 46y2 2.安装教程: (1).下载testNG 离线安装包[ ...
- java中I/O类
总结:输入流/输出流 方法,变量: package com.aini; //流类.输入输出流 import java.io.*; public class rtyeew {// (File file) ...
- PostgreSQL 日常数据库维护工作
日常数据库维护工作定期备份,定期”清理“数据库,周期性的日志文件管理check_postgres可用于检测数据库的健康并报告异常情况 1. 日常清理 PostgreSQL数据库要求周期性的清理维护.对 ...