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. (转)SPFA算法

    原文地址:http://www.cnblogs.com/scau20110726/archive/2012/11/18/2776124.html 粗略讲讲SPFA算法的原理,SPFA算法是1994年西 ...

  2. Codeforces Round #258 (Div. 2)C(暴力枚举)

    就枚举四种情况,哪种能行就是yes了.很简单,关键是写法,我写的又丑又长...看了zhanyl的写法顿时心生敬佩.写的干净利落,简直美如画...这是功力的体现! 以下是zhanyl的写法,转载在此以供 ...

  3. PHP JSON文件解析并获取key、value,判断key是否存在

    /****************************************************************************** * PHP JSON文件解析并获取key ...

  4. Jupyterhub Error 503: Proxy Target Missing

    Jupyterhub Error 503: Proxy Target Missing 请求太频繁

  5. Python 2.7_多进程获取简书专题数据(一)

    学python几个月了正好练练手,发现问题不断提高,先从专题入手,爬取些数据,一开始对简书网站结构不熟悉,抓取推荐,热门,城市3个导航栏,交流发现推荐和热门是排序不同,url会重复,以及每个专题详情页 ...

  6. lower_bound()函数与quicksort()函数的简单掌握

    lower_bound 这个序列中可能会有很多重复的元素,也可能所有的元素都相同,为了充分考虑这种边界条件,STL中的lower_bound算法总体上是才用了二分查找的方法,但是由于是查找序列中的第一 ...

  7. java代码异常处理

    总结:运用throw和throws抛出异常,在哪一种情况下该怎么抛出异常.重要 package com.b; //异常中throwe和throws的用法 public class yz { publi ...

  8. 四川第七届 I Travel(bfs)

    Travel The country frog lives in has nn towns which are conveniently numbered by 1,2,…,n1,2,…,n. Amo ...

  9. Rails的静态资源管理(四)—— 生产环境的 Asset Pipeline

    官方文档:http://guides.ruby-china.org/asset_pipeline.html http://guides.rubyonrails.org/asset_pipeline.h ...

  10. Python代码规范总结

    1.缩进问题: Tip:用4个空格来缩进代码 不要用Tab键或者是Tab和空格混用, vim用户可以将tab键设置为4个空格的长度.要么选择垂直对齐换行的元素, 或者是使用4空格悬挂式缩进(第一行没有 ...