接触LinqTosql是很久的事情了,之前一直在拼接字符串,所以一开始就很喜欢这种ORM的方式,强类型用的爽啊,最近开始
改为学习ADO.NET 实体框架了:),概念上的东西网上都很多,当我想实现一个简单的外键表操作时,却没有一个较好的例子,
经过一段摸索后,将最简单的情形给贴出来。
本文用这2种方式通过一个简单的外键关系来演示Insert,Update,Delete操作
DB中建立2张表,这里只考虑1对多的关系:
LinqToSql的方式:
生成的TestDB.dbml:
Insert:
using(TestDBDataContext db=new TestDBDataContext())
{
Depatment depatment = new Depatment() {DeptName = "开发部"};
Employee employee = new Employee()
{
EmpName = "Ringgo.Yao",
Depatment = depatment
};
db.Depatment.InsertOnSubmit(depatment);
db.SubmitChanges();
}
当提交Department时,会自动提交Employee
Update:
using (TestDBDataContext db = new TestDBDataContext())
{
Depatment depatment = db.Depatment.Where(i => i.DeptId ==2).First();
depatment.DeptName = "研发部";
Employee employee = new Employee()
{
EmpName = "Ringgo.Yao",
Depatment = depatment
};
db.SubmitChanges();
}
这里修改Department记录的同时添加了一条Employee记录
Delete:
using (TestDBDataContext db = new TestDBDataContext())
{
Depatment depatment=db.Depatment.Where(i => i.DeptId == 3).First();
var employees=db.Employee.Where(i => i.DeptId == 3).ToList();
db.Employee.DeleteAllOnSubmit(employees);
db.Depatment.DeleteOnSubmit(depatment);
db.SubmitChanges();
}
删除的时候要先删除Employee,再删除Department
ADO.NET Entity Framework的方式:
生成的TestDB.edmx:
因为代码看起来似乎区别不大,所以就不进行说明了
Insert:
using(TestDBEntities db=new TestDBEntities())
{
Depatment depatment = new Depatment() {DeptName = "开发部"};
Employee employee = new Employee() {EmpName = "Ringgo.Yao"};
depatment.Employee.Add(employee);
db.Depatment.AddObject(depatment);
db.SaveChanges();
}
Update:
using (TestDBEntities db = new TestDBEntities())
{
var dept = db.Depatment.Where(i => i.DeptId == 1).First();
dept.DeptName = "研发部";
Employee employee = new Employee() {EmpName = "White"};
dept.Employee.Add(employee);
db.SaveChanges();
}
Delete:
using (TestDBEntities db = new TestDBEntities())
{
var dept = db.Depatment.Where(i => i.DeptId == 1).First();
foreach (var emp in dept.Employee.ToList())
{
dept.Employee.Remove(emp);
db.Employee.DeleteObject(emp);
}
db.Depatment.DeleteObject(dept);
db.SaveChanges();
}