使用主键属性

每个实体必须有主键

默认值的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. jquery的json的遍历

    jquery遍历解析json对象1: var json = [{dd:'SB',AA:'东东',re1:123},{cccc:'dd',lk:'1qw'}]; for(var i=0,l=json.l ...

  2. vs 2015 update 3各版本下载地址

    微软在06月27日发布了Visual Studio 2015 Update 3 .在MSDN中微软也提供下载,而且MSDN的Visual Studio 2015 Update 3与官方免费下载的文件是 ...

  3. watch 命令

    watch是一个非常实用的命令,基本所有的Linux发行版都带有这个小工具,如同名字一样,watch可以帮你监测一个命令的运行结果,省得你一遍遍的手动运行.在Linux下,watch是周期性的执行下个 ...

  4. Swift迎来了1.0 GM 版(2014.09.09)

    2014年6月2日,swift开发团队将swift语言公之于众.而2014年9月9日迎来了swift的第二个里程碑,swift1.0版本号(GM),这意味着无论你的应用有一部分功能是用swift写的, ...

  5. 机器学习10—K-均值聚类学习笔记

    机器学习实战之K-Means算法 test10.py #-*- coding:utf-8 import sys sys.path.append("kMeans.py") impor ...

  6. mac上搭建docker镜像私服

    1.创建私服容器 docker run -d -e SETTINGS_FLAVOR=dev -e STORAGE_PATH=/tmp/registry -v /opt/data/registry:/t ...

  7. 【Python+selenium】之奇怪问题总结

    问题1: <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> Time Elapsed: 0:00:04 ...

  8. 浅谈Java数据结构和算法

    今天的突然看集合底层的时候发现了好多算法和数据结构.再次就比较一下和汇总一下. 数据结构分类:线性结构和非线性结构 问题一: 什么是线性和非线性: 我个人的理解是:数据结构中线性结构指的是数据元素之间 ...

  9. Live555 中的客户端openRTSP 保存H264文件

    http://amitapba.blog.163.com/blog/static/20361020720140189239762/ http://amitapba.blog.163.com/blog/ ...

  10. JavaScript提高:002:ASP.NET使用easy UI实现tab效果

    近期在做ASP.NET项目中,须要实现一个tab页控件. 发现asp.net控件中没找到现成的. 一般的实现都须要js和div配合.于是就用到了easyui里面的. 使用也非常easy.将easyui ...