使用主键属性

每个实体必须有主键

默认值的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. maven依赖json-lib失败

    © 版权声明:本文为博主原创文章,转载请注明出处 项目中需要使用到JSONArray,因此到将json-lib的依赖加入pom.xml中,但是一直下载失败 <dependency> < ...

  2. 搭建SSH框架整合Struts2和Spring时,使用@Autowired注解无法自动注入

    © 版权声明:本文为博主原创文章,转载请注明出处 1.问题描述: 搭建SSH框架,在进行Struts2和Spring整合时,使用Spring的@Autowired自动注入失败,运行报错java.lan ...

  3. Google Code Jam 2014 资格赛:Problem C. Minesweeper Master

    Problem Minesweeper is a computer game that became popular in the 1980s, and is still included in so ...

  4. c++学习笔记4,派生类的构造函数与析构函数的调用顺序(一)

    測试源代码: //測试派生类的构造函数的调用顺序何时调用 //Fedora20 gcc version=4.8.2 #include <iostream> using namespace ...

  5. MySQL慢查询(二) - pt-query-digest详解慢查询日志 pt-query-digest 慢日志分析

    随笔 - 66 文章 - 0 评论 - 19 MySQL慢查询(二) - pt-query-digest详解慢查询日志 一.简介 pt-query-digest是用于分析mysql慢查询的一个工具,它 ...

  6. thinkPHP5.0的学习研究【基础】

    2017年6月19日13:25:56 基础:1.ThinkPHP5的环境要求如下: PHP >= 5.4.0        PDO PHP Extension        MBstring P ...

  7. linux下nginx安装php

    把php安装包上传到linux的/usr/local/src 1.解压 cd /usr/local/src tar zxvf php-5.6.9.tar.gz cd php-5.6.9 2.编译安装 ...

  8. 浅谈<持续集成、持续交付、持续部署>(二)

    集成是指软件个人研发的部分向软件整体部分交付,以便尽早发现个人开发部分的问题:部署是代码尽快向可运行的开发/测试节交付,以便尽早测试:交付是指研发尽快向客户交付,以便尽早发现生产环境中存在的问题.如果 ...

  9. 【BZOJ2081】[Poi2010]Beads hash+调和级数

    [BZOJ2081][Poi2010]Beads Description Zxl有一次决定制造一条项链,她以非常便宜的价格买了一长条鲜艳的珊瑚珠子,她现在也有一个机器,能把这条珠子切成很多块(子串), ...

  10. Storm编程模型及Worker通信机制

    1.编程模型 2.Worker通信机制