使用主键属性

每个实体必须有主键

默认值的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. H5中滚动卡顿的问题

    加入-webkit-overflow-scrolling: touch;即可

  2. java数字签名算法之RSA

    © 版权声明:本文为博主原创文章,转载请注明出处 实例 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...

  3. angularjs2中的非父子组件的通信

    AngualrJs2官方方法是以@Input,@Output来实现组件间的相互传值,而且组件之间必须父子关系,下面给大家提供一个简单的方法,实现组件间的传值,不仅仅是父子组件,跨模块的组件也可以实现传 ...

  4. linux vmware提示:此虚拟机似乎正在使用中,取得该虚拟机的所有权失败错误

    用vm的时候,没有挂起和关闭虚拟机,直接关实体机.然后不幸的就异常了. 然后今天用的时候提示 此虚拟机似乎正在使用中. 如果此虚拟机已在使用中,请按“取消”按钮,以免损坏它.如果此虚拟机未使用,请按“ ...

  5. DFS应用——找出无向图的割点

    [0]README 0.1) 本文总结于 数据结构与算法分析, 源代码均为原创, 旨在 理解 "DFS应用于找割点" 的idea 并用源代码加以实现: 0.2) 必须要事先 做个s ...

  6. Linq系列(7)——表达式树之ExpressionVisitor

    大家好,由于今天项目升级,大家都在获最新代码,所以我又有时间在这里写点东西,跟大家分享. 在上一篇的文章中我介绍了一个dll,使大家在debug的时候可以可视化的看到ExpressionTree的Bo ...

  7. xcrun: error: unable to find utility "instruments", not a developer tool or in PATH

    xcrun: error: unable to find utility "instruments", not a developer tool or in PATH   用web ...

  8. DICOM:C-GET服务

    背景: 之前博文对照过多次C-MOVE与C-GET服务的差别,两者最大的差别在于C-GET是基于单个TCP连接的点对点的双方服务.而C-MOVE是基于两个TCP连接的三方服务(详情參见:<DIC ...

  9. [Sdoi2013]随机数生成器(BSGS)

    #include<cstdio> #include<cstring> #include<cmath> #include<iostream> #inclu ...

  10. 九度OJ 1356:孩子们的游戏(圆圈中最后剩下的数) (约瑟夫环)

    时间限制:10 秒 内存限制:32 兆 特殊判题:否 提交:1333 解决:483 题目描述: 每年六一儿童节,JOBDU都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为JOBDU的资深 ...