利用ObjectContext 進行Select/Insert/Update/Delete
- Init - Create ObjectContext
SchoolEntities schoolContext=new SchoolEntities();
// init
SchoolEntities schoolContext=new SchoolEntities();
// 取出所有的department資料
var departmentList=schoolContext.Departments;
// 取出所有的department資料,
// 並且每一個department因為FK設定,都可以取得對應的Courses.
var departmentIncludeCoursesList=schoolContext.Departments.Include("Courses");
// 取得第一筆department的Courses.
var courseList=departmentIncludeCoursesList[0].Courses;
// LINQ Join
var departmentCourseInfoQuery =
from a in schoolContext.Departments.Include("Courses")
from b in schoolContext.Courses
where a.DepartmentID==b.DepartmentID
select new {a.Name,b.Title};
// init
SchoolEntities schoolContext=new SchoolEntities();
// create Course
Course Course = new Course();
Course.CourseID = 4444;
Course.Title = "insert";
Course.Credits = 4;
Course.DepartmentID = 7;
// insert to ObjectContext
schoolContext.Courses.AddObject(Course);
// save change
schoolContext.SaveChanges();
var Course =
from c in schoolContext.Courses
where c.CourseID == 4444
select c;
Course.First().Title = "AAAA";
schoolContext.SaveChanges();
var Course =
from c in schoolContext.Courses
where c.CourseID == 4444
select c;
schoolContext.Courses.DeleteObject(Course.First());
schoolContext.SaveChanges();
沒有留言:
張貼留言