EF4 中Self-track entity 错误用于单web开发中要注意的地方
Self-track entity 增删改查注意的地方,由于在单web中没有WCF的序列化和反序列化处理,在更新的时候,单纯的ApplyChanges()无法进行状态的改变,有两种方案
1.在获得对象的时候,用对象的StartTrack 方法来强制开启对象自跟踪。
2.由于第一种方法有时候,很难知道对象获取的地方,开启跟踪比较麻烦。我们可以在更新的时候强制设置跟踪状态方法,如:course.MarkAsModified(); 但这个方法也有个不好,我们必须为Add,Delete,Modify进行不同的处理,来调用不同的MarkAs...等状态标记方式。
public class CourseService
{
public void Update(Course course)
{
using (SchoolEntities db = new SchoolEntities())
{
//如果不在同一个Entity Context只能用这种方式
course.MarkAsModified();
db.ApplyChanges("Courses", course);
db.SaveChanges();
}
}
public void Add(Course course)
{
using (SchoolEntities db = new SchoolEntities())
{
db.Courses.AddObject(course);
db.SaveChanges();
}
}
public void Delete(Course course)
{
using (SchoolEntities db = new SchoolEntities())
{
course.MarkAsDeleted();
db.Courses.ApplyChanges(course);
db.SaveChanges();
}
}
//关联删除
public void DeleteDepartment(int did)
{
using (SchoolEntities db = new SchoolEntities())
{
var department = db.Departments.Include("Courses").FirstOrDefault(d => d.DepartmentID == did);
//必须先ToList,不知道为什么
foreach(var c in department.Courses.ToList())
{
db.DeleteObject(c);
}
db.DeleteObject(department);
//如果不在同一个entity context下,要用标记的方式
//department.MarkAsDeleted();
//db.Departments.ApplyChanges(department);
db.SaveChanges();
}
}
public Course GetCourse(int id)
{
using (SchoolEntities db = new SchoolEntities())
{
var course=db.Courses.FirstOrDefault(c => c.CourseID == id);
return course;
}
}
}
{
public void Update(Course course)
{
using (SchoolEntities db = new SchoolEntities())
{
//如果不在同一个Entity Context只能用这种方式
course.MarkAsModified();
db.ApplyChanges("Courses", course);
db.SaveChanges();
}
}
public void Add(Course course)
{
using (SchoolEntities db = new SchoolEntities())
{
db.Courses.AddObject(course);
db.SaveChanges();
}
}
public void Delete(Course course)
{
using (SchoolEntities db = new SchoolEntities())
{
course.MarkAsDeleted();
db.Courses.ApplyChanges(course);
db.SaveChanges();
}
}
//关联删除
public void DeleteDepartment(int did)
{
using (SchoolEntities db = new SchoolEntities())
{
var department = db.Departments.Include("Courses").FirstOrDefault(d => d.DepartmentID == did);
//必须先ToList,不知道为什么
foreach(var c in department.Courses.ToList())
{
db.DeleteObject(c);
}
db.DeleteObject(department);
//如果不在同一个entity context下,要用标记的方式
//department.MarkAsDeleted();
//db.Departments.ApplyChanges(department);
db.SaveChanges();
}
}
public Course GetCourse(int id)
{
using (SchoolEntities db = new SchoolEntities())
{
var course=db.Courses.FirstOrDefault(c => c.CourseID == id);
return course;
}
}
}
披荆斩棘,朝自己的信仰!Go on