使用主键属性

每个实体必须有主键

默认值的id属性值必须为0

在context2中,它不知道实体的状态,

只能通过实体的主键来判断实体的状态

如果主键为0,则是新的对象,不为0 就是修改

Standard disconnectedStandard = null;

using (var context = new SchoolDBEntities())
{
context.Configuration.ProxyCreationEnabled = false; disconnectedStandard = context.Standards.Where(s => s.StandardId == 58).Include(s => s.Teachers).FirstOrDefault<Standard>();
}
//Update Standard in disconnected mode
disconnectedStandard.StandardName = "Edited Standard Name"; //Update teachers collection by editing first teacher and adding new teacher
disconnectedStandard.Teachers.ElementAt(0).TeacherName = "Edited Teacher Name";
disconnectedStandard.Teachers.Add(new Teacher() { TeacherName = "New Teacher", StandardId = disconnectedStandard.StandardId }); using (var newContext = new SchoolDBEntities())
{
//mark standard based on StandardId
newContext.Entry(disconnectedStandard).State = disconnectedStandard.StandardId == 0 ? EntityState.Added : EntityState.Modified; //mark teacher based on StandardId
foreach (Teacher tchr in disconnectedStandard.Teachers)
newContext.Entry(tchr).State = tchr.TeacherId == 0 ? EntityState.Added : EntityState.Modified; newContext.SaveChanges();
}

使用主键的好处有:

1.不需要多余的代码来决定实体的状态

2.良好的性能

不好的地方有 ;

1.每个实体都需要有主键,没有主键就不能确定实体的状态

2.不能决定unchanged状态的实体,如果实体没有改变也会被设置为modified状态,这就没必要去更新没有改变的实体

3.不能删除实体

方法2:

设置实体的State属性

首先,创建一个带有枚举参数的接口

interface IEntityObjectState
{
EntityObjectState ObjectState { get; set; }
} public enum EntityObjectState
{
Added,
Modified,
Deleted,
Unchanged
}

其次,每个实体都实现该接口

public partial class Standard:IEntityObjectState
{
public Standard()
{
this.Students = new HashSet<Student>();
this.Teachers = new HashSet<Teacher>();
} public int StandardId { get; set; }
public string StandardName { get; set; }
public string Description { get; set; } public virtual ICollection<Student> Students { get; set; }
public virtual ICollection<Teacher> Teachers { get; set; }
[NotMapped]
public EntityObjectState ObjectState
{
get;
set;
}
} public partial class Teacher:IEntityObjectState
{
public Teacher()
{
this.Courses = new HashSet<Course>();
} public int TeacherId { get; set; }
public string TeacherName { get; set; }
public Nullable<int> StandardId { get; set; } public virtual ICollection<Course> Courses { get; set; }
public virtual Standard Standard { get; set; } [NotMapped]
public EntityObjectState ObjectState
{
get;
set;
} }

在客户端设置实体的状态

Teacher existingTeacher = null;

using (var context = new SchoolDBEntities())
{
context.Configuration.ProxyCreationEnabled = false;
existingTeacher = context.Teachers.FirstOrDefault<Teacher>(); }
Standard disconnectedStandard = new Standard() { StandardName = "New Standard", ObjectState = EntityObjectState.Added };
existingTeacher.ObjectState = EntityObjectState.Modified;
//add existing teacher(in db) to standard
disconnectedStandard.Teachers.Add(existingTeacher);
//add new standard
disconnectedStandard.Teachers.Add(new Teacher() { TeacherName = "New teacher", StandardId = disconnectedStandard.StandardId, ObjectState = EntityObjectState.Added });
using (var newContext = new SchoolDBEntities())
{
//check the ObjectState property and mark appropriate EntityState
if (disconnectedStandard.ObjectState == EntityObjectState.Added)
newContext.Entry(disconnectedStandard).State = System.Data.Entity.EntityState.Added;
else if (disconnectedStandard.ObjectState == EntityObjectState.Modified)
newContext.Entry(disconnectedStandard).State =System.Data.Entity.EntityState.Modified;
else if (disconnectedStandard.ObjectState == EntityObjectState.Deleted)
newContext.Entry(disconnectedStandard).State = System.Data.Entity.EntityState.Deleted;
else
newContext.Entry(disconnectedStandard).State = System.Data.Entity.EntityState.Unchanged; //check the ObjectState property of each teacher and mark appropriate EntityState
foreach (Teacher tchr in disconnectedStandard.Teachers)
{
if (tchr.ObjectState == EntityObjectState.Added)
newContext.Entry(tchr).State = System.Data.Entity.EntityState.Added;
else if (tchr.ObjectState == EntityObjectState.Modified)
newContext.Entry(tchr).State = System.Data.Entity.EntityState.Modified;
else if (tchr.ObjectState == EntityObjectState.Deleted)
newContext.Entry(tchr).State = System.Data.Entity.EntityState.Deleted;
else
newContext.Entry(tchr).State = System.Data.Entity.EntityState.Unchanged;
}
//save changes
newContext.SaveChanges();
}

EntityFramework 学习 一 Update Entity Graph using DbContext:的更多相关文章

  1. EntityFramework 学习 一 Add Entity Graph using DbContext:

    //Create student in disconnected mode Student newStudent = new Student() { StudentName = "New S ...

  2. Entity Framework Tutorial Basics(27):Update Entity Graph

    Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...

  3. EntityFramework 学习 一 Update Existing Entity using DBContext in Disconnected Scenario

    using System; using System.Collections.Generic; public partial class Student { public Student() { th ...

  4. EntityFramework 学习 一 Delete Entity using DBContext in Disconnected Scenario

    Student studentToDelete; . Get student from DB using (var ctx = new SchoolDBEntities()) { studentToD ...

  5. EntityFramework 学习 一 Validate Entity

    可以为实体实现自定义验证,重写DBContext中的个ValidateEntity方法 protected override System.Data.Entity.Validation.DbEntit ...

  6. EntityFramework 学习 一 Colored Entity in Entity Framework 5.0

    You can change the color of an entity in the designer so that it would be easy to see related groups ...

  7. Entity Framework Tutorial Basics(26):Add Entity Graph

    Add Entity Graph using DbContext: Adding entity graph with all new entities is a simple task. We can ...

  8. EntityFramework 学习 一 Disconnected Entities

    如何把断开的实体添加到新的context上下文中 1.首先,我们需要把实体附加到新的context上下文实例中. 2.其次,手动的给实体设置适当的实体状态,因为新的context上下文不知道断开的实体 ...

  9. Entityframework:“System.Data.Entity.Internal.AppConfig”的类型初始值设定项引发异常。

    <configSections> <!-- For more information on Entity Framework configuration, visit http:// ...

随机推荐

  1. 自己定义控件三部曲视图篇(二)——FlowLayout自适应容器实现

    前言:我最大的梦想,就是有一天.等老了坐在摇椅上回望一生,有故事给孩子们讲--. 相关文章: <Android自己定义控件三部曲文章索引>:http://blog.csdn.net/har ...

  2. windows下忘记mysql超级管理员rootpassword的解决的方法

    今天帮一个朋友找回了MYSQL的超级管理员ROOTpassword.開始输入命令的时候少打了个"点"害的折腾了几个小时.最终攻克了,写个教程,方便以后使用! 假设你是server是 ...

  3. oracle中直方图的使用

    本文从不绑定变量和绑定变量两种情况讨论直方图的作用 一.不绑定变量 SQL> create table test(name varchar2(10));表已创建.SQL> insert i ...

  4. MyBatis随笔

    前一阵参与了一个项目的搭建,为了快速开发再加上学一些新东西,准备采用React+Spring MVC+MyBatis的架构. 花了一些时间最终把Spring MVC+MyBatis打通. 这里总结下M ...

  5. 关于并发模型 Actor 和 CSP

    最近在看<七天七并发模型>这本书,在书上介绍了 Actor 和 CSP 这两种并发模型.这两种模型很像,但还是有一些不同的地方.看完之后,比较困扰的是: 在什么场合使用哪种模型比较好呢? ...

  6. DFS应用——查找强分支

    [0]README 0.1) 本文总结于 数据结构与算法分析, 源代码均为原创, 旨在 理解 "DFS应用--查找强分支" 的idea 并用源代码加以实现 : [1]查找强分支 1 ...

  7. Unity5 怎样做资源管理和增量更新

    工具 Unity 中的资源来源有三个途径:一个是Unity自己主动打包资源.一个是Resources.一个是AssetBundle. Unity自己主动打包资源是指在Unity场景中直接使用到的资源会 ...

  8. Lumen开发:lumen源码解读之初始化(3)——单例(singleton)与中间件(Middleware)

    版权声明:本文为博主原创文章,未经博主允许不得转载. 今天来讲讲Lumen的singleton和Middleware,先来看看起始文件bootstrap/app.php / * | --------- ...

  9. Java多态案例分析

    一.多态的定义 同一事物,在不同时刻体现出不同状态. 例如:水在不同状态可能是:气态.液态.固态. 二.多态前提和体现 1.有继承关系 2.有方法重写 3.有父类引用指向子类对象 三.编译运行原理 1 ...

  10. iOS 3DES加密

    本文转载至 http://www.cocoachina.com/bbs/read.php?tid=177167 -(NSString *)TripleDES:(NSString *)plainText ...