Welcome

首页 / 软件开发 / .NET编程技术 / ADO.NET Entity Framework深入分析, Part 5

ADO.NET Entity Framework深入分析, Part 52010-09-10EntLib前面的Part 1-4的文章,介绍了Entity Data Model、Entity SQL、ObjectQuery、EntityCommand、LINQ to Entities等等及其代码演示。Part 4主要演示如何通过相关技术或Debug工具,如SQL Server Profiler、ToTraceString 方法、eSqlBlast 工具、LINQPad工具等等,来查看生成的T-SQL脚本。本篇文章Part 5 演示如何新增、更新和删除数据实体,并相应更新数据库。

增加、更新和删除实体

将实体的更新操作应用到数据库很方便。对象服务(Object Services)将记录所有对实体对象的改变,并产生和执行相应的T-SQL语句,对数据库实施插入、更新和删除操作。

通过调用ObjectContext的SaveChanges() 方法,来实现对数据库的更新,这与LINQ to SQL 的DataContext的SubmitChanges() 方法比较相似。

更新或修改实体

NorthwindEntities context = new NorthwindEntities();

Employee firstEmployee = context.Employees.First(e => e.EmployeeID == 1);

if (firstEmployee != null)
{
firstEmployee.City = "San Francisco";
firstEmployee.Notes = "New notes for employee 1";
int affected = context.SaveChanges();
}

1) 检索一个Employee

LINQ to Entities 中,你可以使用扩展方法First(),因为SingleOrDefault() 方法将抛出NotSupportedException 异常(The "Single" operator is not supported by LINQ to Entities. Consider using "First" instead)。

2) 改变实体的一些属性

3) 调用ObjectContext 的SaveChanges() 方法,该方法将返回增加、修改或删除的实体对象的数量。