EntityFramework 学习 一 Update Entity Graph using DbContext:
使用主键属性
每个实体必须有主键
默认值的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:的更多相关文章
- EntityFramework 学习 一 Add Entity Graph using DbContext:
//Create student in disconnected mode Student newStudent = new Student() { StudentName = "New S ...
- Entity Framework Tutorial Basics(27):Update Entity Graph
Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...
- EntityFramework 学习 一 Update Existing Entity using DBContext in Disconnected Scenario
using System; using System.Collections.Generic; public partial class Student { public Student() { th ...
- EntityFramework 学习 一 Delete Entity using DBContext in Disconnected Scenario
Student studentToDelete; . Get student from DB using (var ctx = new SchoolDBEntities()) { studentToD ...
- EntityFramework 学习 一 Validate Entity
可以为实体实现自定义验证,重写DBContext中的个ValidateEntity方法 protected override System.Data.Entity.Validation.DbEntit ...
- 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 ...
- 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 ...
- EntityFramework 学习 一 Disconnected Entities
如何把断开的实体添加到新的context上下文中 1.首先,我们需要把实体附加到新的context上下文实例中. 2.其次,手动的给实体设置适当的实体状态,因为新的context上下文不知道断开的实体 ...
- Entityframework:“System.Data.Entity.Internal.AppConfig”的类型初始值设定项引发异常。
<configSections> <!-- For more information on Entity Framework configuration, visit http:// ...
随机推荐
- PLSQL中显示Cursor、隐示Cursor、动态Ref Cursor差别
一.显式cursor 显式是相对与隐式cursor而言的,就是有一个明白的声明的cursor.显式游标的声明类似例如以下(具体的语法參加plsql ref doc ): cursor cursor_n ...
- [译]GLUT教程 - 整合代码6
Lighthouse3d.com >> GLUT Tutorial >> Extras >> The Code So Far VI 下面代码以窗体模式启动.你可以在 ...
- ffmpeg截图
ffmpeg.exe -probesize 32768 -i "rtmp://localhost/live/1 live=1" -y -t 0.001 -ss 1 -f image ...
- Project Euler:Problem 87 Prime power triples
The smallest number expressible as the sum of a prime square, prime cube, and prime fourth power is ...
- 蒙特卡洛方法计算圆周率的三种实现-MPI openmp pthread
蒙特卡洛方法实现计算圆周率的方法比较简单,其思想是假设我们向一个正方形的标靶上随机投掷飞镖,靶心在正中央,标靶的长和宽都是2 英尺.同时假设有一个圆与标靶内切.圆的半径是1英尺,面积是π平方英尺.如果 ...
- CLR内存回收总结,代龄机制
关键字:对象可达图,代龄机制,终止化对象. 代龄机制: 0代满了之后,GC开始回收,剩下的对象升级为1代.(只有不可达的对象才会被回收.) 0代再回收几次之后,1代的对象慢慢增多然后达到阈值,GC同时 ...
- 多媒体开发之---H264—MP4格式及在MP4文件中提取H264的SPS、PPS及码流
一.MP4格式基本概念 MP4格式对应标准MPEG-4标准(ISO/IEC14496) 二.MP4封装格式核心概念 1 MP4封装格式对应标准为 ISO/IEC 14496-12(信息技术 视听对象 ...
- Unity导出AssetBundle到指定路径
using System.Collections; using UnityEngine; using UnityEditor; using System.IO; /// <summary> ...
- Netty实战
一.Netty异步和事件驱动1.Java网络编程回顾socket.accept 阻塞socket.setsockopt /非阻塞2.NIO异步非阻塞a).nio 非阻塞的关键时使用选择器(java.n ...
- 解决ubuntu中文乱码问题
方法一: Ubuntu默认的中文字符编码为zh_CN.UTF-8,这个可以在 /etc/environment中看到:sudo gedit /etc/environment可以看到如下内容:PATH= ...