Entity Framework Tutorial Basics(22):Disconnected Entities
Disconnected Entities:
Before we see how to perform CRUD operation on disconnected entity graph, let's see how to associate disconnected entity graph with the new context instance.
There are two things we need to do when we get a disconnected entity graph or even a single disconnected entity. First, we need to attach entities with the new context instance and make context aware about these entities. Second, set appropriate EntityStates to these entities manually because the new context instance doesn't know anything about the operations performed on the disconnected entities, so the new context cannot apply the appropriate EntityState.
The following figure illustrates this process.

Entity Framework API provides some important methods that attaches disconnected entities to the new context and also set EntityStates to all the entities of an entity graph.
DbSet.Add():
DbSet.Add() method attaches the entire entity graph to the new context and automatically applies Added entity state to all the entities.
Consider the following example code.
//disconnected entity graph
Student disconnectedStudent = new Student() { StudentName = "New Student" };
disconnectedStudent.StudentAddress = new StudentAddress() { Address1 = "Address", City = "City1" }; using (var ctx = new SchoolDBEntities())
{
//add disconnected Student entity graph to new context instance - ctx
ctx.Students.Add(disconnectedStudent); // get DbEntityEntry instance to check the EntityState of specified entity
var studentEntry = ctx.Entry(disconnectedStudent);
var addressEntry = ctx.Entry(disconnectedStudent.StudentAddress); Console.WriteLine("Student EntityState: {0}",studentEntry.State); Console.WriteLine("StudentAddress EntityState: {0}",addressEntry.State);
}
Student EntityState: Added
StudentAddress EntityState: Added
As per the above example code, we add disconnectedStudent entity graph using ctx.Students.Add method. Here, parent entity is Student, so we have added a whole entity graph in Students DbSet. We then get the DbEntityEntry instance for Student and StudentAddress entities to check the state of each entity. As you can see in the output, both entities have Added state.
Thus, use Add method of parent DbSet entity to attach the entire entity graph to the new context instance with Added state to each entity. This will execute insert command for all the entities, which will insert new rows in the appropriate database table.
DbSet.Attach():
DbSet.Attach method attaches a whole entity graph to the new context with Unchanged entity state.
Consider the following example code.
//disconnected entity graph
Student disconnectedStudent = new Student() { StudentName = "New Student" };
disconnectedStudent.StudentAddress = new StudentAddress() { Address1 = "Address", City = "City1" }; using (var ctx = new SchoolDBEntities())
{
//attach disconnected Student entity graph to new context instance - ctx
ctx.Students.Attach(disconnectedStudent); // get DbEntityEntry instance to check the EntityState of specified entity
var studentEntry = ctx.Entry(disconnectedStudent);
var addressEntry = ctx.Entry(disconnectedStudent.StudentAddress); Console.WriteLine("Student EntityState: {0}",studentEntry.State); Console.WriteLine("StudentAddress EntityState: {0}",addressEntry.State);
}
Student EntityState: Unchanged
StudentAddress EntityState: Unchanged
As per the above code, we can attach disconnected entity graph using DbSet.Attach method. This will attach the entire entity graph to the new context with Unchanged entity state to all entities.
Thus, Attach method will only attach entity graph to the context, so we need to find the appropriate entity state for each entity and apply it manually.
DbContext.Entry():
Entry method of DbContext returns DbEntityEntry instance for a specified entity. DbEntityEntry can be used to change the state of an entity.
DbContext.Entry(disconnectedEntity).state = EntityState.Added/Modified/Deleted/Unchanged
This method attaches a whole entity graph to the context with specified state to the parent entity and set the state of other entities, as shown in the following table.
| Parent Entity State | Entity State of child entities |
|---|---|
| Added | Added |
| Modified | Unchanged |
| Deleted | All child entities will be null |
Entity Framework Tutorial Basics(22):Disconnected Entities的更多相关文章
- Entity Framework Tutorial Basics(1):Introduction
以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...
- Entity Framework Tutorial Basics(19):Change Tracking
Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...
- Entity Framework Tutorial Basics(12):Model First
Model First development with Entity Framework: In the Model First approach, you create Entities, rel ...
- Entity Framework Tutorial Basics(4):Setup Entity Framework Environment
Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...
- Entity Framework Tutorial Basics(43):Download Sample Project
Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...
- Entity Framework Tutorial Basics(42):Colored Entity
Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...
- Entity Framework Tutorial Basics(41):Multiple Diagrams
Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...
- Entity Framework Tutorial Basics(37):Lazy Loading
Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...
- Entity Framework Tutorial Basics(36):Eager Loading
Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...
随机推荐
- Java模版引擎:jsp、freemarker、velocity区别
在java领域,表现层技术主要有三种:jsp.freemarker.velocity. jsp是大家最熟悉的技术优点:1.功能强大,可以写java代码2.支持jsp标签(jsp tag)3.支持表达式 ...
- Yii 常用命令
一.Yii的Active Recorder包装了很多. 特别是把SQL中 把where,order,limit,IN/not IN,like等常用短句都包含进CDbCriteria这个类中去,这样整个 ...
- BZOJ2120:数颜色(分块版)
浅谈分块:https://www.cnblogs.com/AKMer/p/10369816.html 题目传送门:https://lydsy.com/JudgeOnline/problem.php?i ...
- BZOJ1202:[HNOI2005]狡猾的商人
浅谈并查集:https://www.cnblogs.com/AKMer/p/10360090.html 题目传送门:https://lydsy.com/JudgeOnline/problem.php? ...
- c++11之三: sizeof运算符 auto的优势 __func__预定义标识符
在C++11中,对非静态成员变量使用sizeof操作是合法的. auto推导的一个最大优势就是在拥有初始化表达式的复杂类型变量声明时简化代码.如:std:vector<std::string&g ...
- Azure Managed Disk
Azure的磁盘存储是保存在存储账户中的Page Blob.由于Azure Storage Account的各种限制,在设计VM的磁盘存储时,要符合Azure磁盘存储账户的最佳实践,请参考:http: ...
- Day2-Python基础2---字符编码与转码
详细内容http://www.cnblogs.com/yuanchenqi/articles/5956943.html 一.编码介绍: 1.基本概念: 在python 2中默认编码是 ASCII,而在 ...
- python风格指南
还在让别人一眼就看出你是一只野生程序猿嘛,快来看看谷歌的python风格指南提升逼格吧! http://zh-google-styleguide.readthedocs.io/en/latest/go ...
- spring boot 学习10 定义springboot的两种方法
使用spring boot的两种方法: A:继承spring-boot-starter-parent项目 这种方式很简单,只需要在POM里面添加parent父工程即可. B: 如果你不喜欢继承spri ...
- linux串口基本编程
Linux的串口表现为设备文件.Linux的串口设备文件命名一般为/dev/ttySn(n=0.1.2„„),若串口是USB扩展的,则串口设备文件命名多为/dev/ttyUSBn(n=0.1.2„„) ...