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. Mysql系列:高可用(HA)-keeplived

    转自:晓叹星沉 https://my.oschina.net/blueSky4Java/blog/1572905 摘要: 随着项目的发展,为了提高程序的性能,数据库层面或多或少的会用到HA.读写分离. ...

  2. mount: error mounting /dev/root on /sysroot as ext3: Invalid argument

    /************************************************************************ * mount: error mounting /d ...

  3. tests

    test

  4. 多版本python管理miniconda(集成了virtualenv和pip功能)

    miniconda下载地址: https://conda.io/docs/user-guide/install/index.html Installing on Linux Download the ...

  5. bae3.0第二步 添加一个空的django项目

    1.创建django项目: 进入bae应用源码目录(appidd01iud80bg)执行django-admin.py startproject blog2.修改index.py的内容如下所示 #-* ...

  6. iOS播放视频

    1.首先导入 MediaPlayer import MediaPlayer 2.播放事件 class ViewController:UIViewController{ var pc:MPMoviePl ...

  7. AJAX,jQuery Ajax和Deferred

    AJAX全称为“Asynchronous JavaScript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用,改善用户体验,实现无刷新效果的技术. 使用AJAX的优 ...

  8. linux中普通用户修改密码出现(passwd:Authentication token manipulation error)

    如果在linux中,不管是root用户还是普通用户登录后,修改自己的密码,出现---passwd:Authentication token manipulation error---错误的解决办法: ...

  9. java流2

    总结:字符转换 package com.b; //流类 import java.io.*; public class uy { // 读取字符 public static void main(Stri ...

  10. mysql函数之二:left,right,substring,substring_index MySQL截取字符串函数方法

    函数: 1.从左开始截取字符串 left(str, length) 说明:left(被截取字段,截取长度) 例:select left(content,200) as abstract from my ...