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);
}
Output:

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);
}
Output:

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的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. Entity Framework Tutorial Basics(19):Change Tracking

    Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...

  3. Entity Framework Tutorial Basics(12):Model First

    Model First development with Entity Framework: In the Model First approach, you create Entities, rel ...

  4. 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 ...

  5. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  6. 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 ...

  7. Entity Framework Tutorial Basics(41):Multiple Diagrams

    Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...

  8. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  9. 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 ...

随机推荐

  1. linux下的第一个C程序及其编译方法

    #include <stdio.h> #include <stdlib.h>   int main(int argc, char ** argv) {     printf(& ...

  2. UVALive - 3490 Generator (AC自动机+高斯消元dp)

    初始有一个空串s,从前n个大写字母中不断随机取出一个字母添加到s的结尾,出现模式串t时停止,求停止时s的长度期望. 这道题解法不唯一,比较无脑的方法是对模式串t建一个单串AC自动机,设u为自动机上的一 ...

  3. GO语言list剖析

    GO语言list剖析 本节内容 使用方法 list提供的方法 源码剖析 1. 使用方法 在GO语言的标准库中,提供了一个container包,这个包中提供了三种数据类型,就是heap,list和rin ...

  4. bzoj 4827 [Hnoi2017]礼物——FFT

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4827 式子就是 \sum_{i=0}^{n-1}(a[ i ] - b[ i+k ] + c ...

  5. 修改windows文件的换行符

    应用场景: 在办公中,有可能存在,某些命令脚本使用windows下的文本编辑器进行编写 当放到测试环境的Linux中时,运行报错 需要使用的软件:xxd hexdump  dos2unix 1.运行w ...

  6. 在struts2中配置自定义拦截器放行多个方法

    源码: 自定义的拦截器类: //自定义拦截器类:LoginInterceptor ; package com.java.action.interceptor; import javax.servlet ...

  7. Anti-pattern(反模式)

    常见的与“直觉”相背离的 anti-pattern 产生的实际原因是我们没有深入全面地考虑问题. 即只关注到自己关心的方面,忽略了其他重要的.恰好起相反作用的因素. 所以这个“直觉”是不成熟.不全面的 ...

  8. java代码继承基础

    总结:继承是java编程的核心,我搞不明白,子类对象调用父类的成员方法时.父类的带参构造方法有什么用,还赋值了 package com.bc; //普通类 public class yt { publ ...

  9. Redis 复制技术和高可用sentinel(哨兵模式)

    redis的复制技术和高可用(哨兵模式) 1 复制 为什么要复制 实现数据的多副本存储,从而可以实现服务的高可用 提供更好的读性能复制技术的关键点及难点 如何指定被复制对象 增量还是全量以及如何实现增 ...

  10. 第九课 go的循环语句

    1 for语句的三种形式 /* for 循环 */ ; a < ; a++ { fmt.Printf("a 的值为: %d\n", a) } var a, b int = 1 ...