- 浏览: 1067867 次
- 性别:
- 来自: 长沙
文章分类
- 全部博客 (639)
- 服务器配置篇 (58)
- hibernate篇 (14)
- spring篇 (33)
- struts篇 (28)
- JS篇 (46)
- 其他技术篇 (46)
- 数据库集群配置 (6)
- JAVA基础相关 (48)
- 分布式框架HadHoop的应用 (2)
- FLEX篇 (8)
- SQLSERVER技术 (32)
- Android学习 (13)
- amchart学习笔记 (1)
- openfire+smark搭建即时通讯 (9)
- Linux学习 (18)
- Oracle数据库 (15)
- 网站优化技术 (12)
- mysql数据库 (2)
- 项目学习总结 (18)
- 工具类(JAVA) (12)
- 工具类(JS) (2)
- 设计模式 (10)
- Lucene学习 (24)
- EJB3学习 (6)
- Sphinx搜索引擎 (3)
- 工作中用到的软件小工具 (5)
- .NET (49)
- JAVA 连接SQLSERVER2008步骤 (1)
- MongoDB (19)
- Android手机开发 (3)
- Maven (6)
- vue (9)
- Shiro (4)
- mybatis (3)
- netty框架 (1)
- SpringCloud (3)
- spring-cloud (7)
- Git (1)
- dubbo (2)
- springboot (13)
- rocketmq (1)
- git学习 (2)
- kafka服务器 (2)
- linux (10)
- WEB系统辅助项目 (1)
- jenkins (2)
- docker (4)
- influxdb (3)
- python (2)
- nginx (1)
最新评论
-
jiangfuofu555:
这样数据量大,效率怎么样?
sqlserver 实现分页的前台代码 以及后台的sqlserver语句 -
w156445045:
博主请问下,如何做到实时的刷新呢,
另外我后台是Java 谢谢 ...
web 版本的汽车仪表盘,非常好看。还有各种图形 -
jackyin5918:
<transportConnector name=&qu ...
ActiveMQ的activemq.xml详细配置讲解 -
握着橄榄枝的人:
你这个不是spring1.x的吧
spring1.x使用AOP实例 -
xiaophai:
全乱套了!
openfire+spark搭建完美的及时通讯
In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server Compact. In this tutorial you will review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.
Note It's a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data access layer. To keep these tutorials simple, you won't implement a repository until a later tutorial in this series (Implementing the Repository and Unit of Work Patterns).
In this tutorial, you will create the following web pages:
Creating a Details Page
The scaffolded code for the Index page left out the Enrollments
property, because that property holds a collection. In the Details page you will display the contents of the collection in an HTML table.
In Controllers\StudentController.cs, the action method for the Details view resembles the following example:
public ViewResult Details(int id) { Student student = db.Students.Find(id); return View(student); }
The code uses the Find
method to retrieve a single Student
entity corresponding to the key value that's passed to the method as the id
parameter. The id
value comes from a query string in the Details hyperlink on the Index page.
Open Views\Student\Details.cshtml. Each field is displayed using a DisplayFor
helper, as shown in the following example:
<div class="display-label">LastName</div> <div class="display-field"> @Html.DisplayFor(model => model.LastName) </div>
To display a list of enrollments, add the following code after the EnrollmentDate
field, immediately before the closing fieldset
tag:
<div class="display-label"> @Html.LabelFor(model => model.Enrollments) </div> <div class="display-field"> <table> <tr> <th>Course Title</th> <th>Grade</th> </tr> @foreach (var item in Model.Enrollments) { <tr> <td> @Html.DisplayFor(modelItem => item.Course.Title) </td> <td> @Html.DisplayFor(modelItem => item.Grade) </td> </tr> } </table> </div>
This code loops through the entities in the Enrollments
navigation property. For each Enrollment
entity in the property, it displays the course title and the grade. The course title is retrieved from the Course
entity that's stored in the Course
navigation property of the Enrollments
entity. All of this data is retrieved from the database automatically when it's needed. (In other words, you are using lazy loading here. You did not specify eager loading for the Courses
navigation property, so the first time you try to access that property, a query is sent to the database to retrieve the data. You can read more about lazy loading and eager loading in the Reading Related Data tutorial later in this series.)
Run the page by selecting the Students tab and clicking a Details hyperlink. You see the list of courses:
Creating a Create Page
In Controllers\StudentController.cs, replace the HttpPost
Create
action method with the following code to add a try-catch
block to the scaffolded method:
[HttpPost] public ActionResult Create(Student student) { try { if (ModelState.IsValid) { db.Students.Add(student); db.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(student); }
This code adds the Student
entity created by the ASP.NET MVC model binder to the Students
entity set and then saves the changes to the database. (Model binder refers to the ASP.NET MVC functionality that makes it easier for you to work with data submitted by a form; a model binder converts posted form values to .NET Framework types and passes them to the action method in parameters. In this case, the model binder instantiates a Student
entity for you using property values from the Form
collection.)
The try-catch
block is the only difference between this code and what the automatic scaffolding created. If an exception that derives from DataException
is caught while the changes are being saved, a generic error message is displayed. These kinds of errors are typically caused by something external to the application rather than a programming error, so the user is advised to try again. The code in Views\Student\Create.cshtml is similar to what you saw in Details.cshtml, except that EditorFor
and ValidationMessageFor
helpers are used for each field instead of DisplayFor
. The following example shows the relevant code:
<div class="editor-label"> @Html.LabelFor(model => model.LastName) </div> <div class="editor-field"> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div>
No changes are required in Create.cshtml.
Run the page by selecting the Students tab and clicking Create New.
Data validation works by default. Enter names and an invalid date and click Create to see the error message.
In this case you're seeing client-side validation that's implemented using JavaScript. But server-side validation is also implemented. Even if client validation failed, bad data would be caught and an exception would be thrown in server code.
Change the date to a valid value such as 9/1/2005 and click Create to see the new student appear in the Index page.
Creating an Edit Page
In Controllers\StudentController.cs, the HttpGet
Edit
method (the one without the HttpPost
attribute) uses the Find
method to retrieve the selected Student
entity, as you saw in the Details
method. You don't need to change this method.
However, replace the HttpPost
Edit
action method with the following code to add a try-catch
block:
[HttpPost] public ActionResult Edit(Student student) { try { if (ModelState.IsValid) { db.Entry(student).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException) { //Log the error (add a variable name after DataException) ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(student); }
This code is similar to what you saw in the HttpPost
Create
method. However, instead of adding the entity created by the model binder to the entity set, this code sets a flag on the entity that indicating it has been changed. When the SaveChanges
method is called, the Modified
flag causes the Entity Framework to create SQL statements to update the database row. All columns of the database row will be updated, including those that the user didn't change, and concurrency conflicts are ignored. (You will learn how to handle concurrency in the Handling Concurrency tutorial later in this series.)
Entity States and the Attach and SaveChanges Methods
The database context keeps track of whether entities in memory are in sync with their corresponding rows in the database, and this information determines what happens when you call the SaveChanges
method. For example, when you pass a new entity to the Add
method, that entity's state is set to Added
. Then when you call the SaveChanges
method, the database context issues a SQL INSERT
command.
An entity may be in one of the following states:
-
Added
. The entity does not yet exist in the database. TheSaveChanges
method must issue anINSERT
statement. -
Unchanged
. Nothing needs to be done with this entity by theSaveChanges
method. When you read an entity from the database, the entity starts out with this status. -
Modified
. Some or all of the entity's property values have been modified. TheSaveChanges
method must issue anUPDATE
statement. -
Deleted
. The entity has been marked for deletion. TheSaveChanges
method must issue aDELETE
statement. -
Detached
. The entity isn't being tracked by the database context.
In a desktop application, state changes are typically set automatically. In this type of application, you read an entity and make changes to some of its property values. This causes its entity state to automatically be changed to Modified
. Then when you call SaveChanges
, the Entity Framework generates a SQL UPDATE
statement that updates only the actual properties that you changed.
However, in a web application this sequence is interrupted, because the database context instance that reads an entity is disposed after a page is rendered. When the HttpPost
Edit
action method is called, this is the result of a new request and you have a new instance of the context, so you have to manually set the entity state to Modified.
Then when you call SaveChanges
, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed.
If you want the SQL Update
statement to update only the fields that the user actually changed, you can save the original values in some way (such as hidden fields) so that they are available when the HttpPost
Edit
method is called. Then you can create a Student
entity using the original values, call the Attach
method with that original version of the entity, update the entity's values to the new values, and then call SaveChanges.
For more information, see Add/Attach and Entity States and Local Data on the Entity Framework team blog.
The code in Views\Student\Edit.cshtml is similar to what you saw in Create.cshtml, and no changes are required.
Run the page by selecting the Students tab and then clicking an Edit hyperlink.
Change some of the data and click Save. You see the changed data in the Index page.
Creating a Delete Page
In Controllers\StudentController.cs, the template code for the HttpGet
Delete
method uses the Find
method to retrieve the selected Student
entity, as you saw in the Details
and Edit
methods. However, to implement a custom error message when the call to SaveChanges
fails, you will add some functionality to this method and its corresponding view.
As you saw for update and create operations, delete operations require two action methods. The method that is called in response to a GET request displays a view that gives the user a chance to approve or cancel the delete operation. If the user approves it, a POST request is created. When that happens, the HttpPost
Delete
method is called and then that method actually performs the delete operation.
You will add a try-catch
block to the HttpPost
Delete
method to handle any errors that might occur when the database is updated. If an error occurs, the HttpPost
Delete
method calls the HttpGet
Delete
method, passing it a parameter that indicates that an error has occurred. The HttpGet Delete
method then redisplays the confirmation page along with the error message, giving the user an opportunity to cancel or to try again.
Replace the HttpGet
Delete
action method with the following code, which manages error reporting:
public ActionResult Delete(int id, bool? saveChangesError) { if (saveChangesError.GetValueOrDefault()) { ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists see your system administrator."; } return View(db.Students.Find(id)); }
This code accepts an optional Boolean parameter that indicates whether it was called after a failure to save changes. This parameter is null (false
) when the HttpGet
Delete
method is called in response to a page request. When it is called by the HttpPost
Delete
method in response to a database update error, the parameter is true
and an error message is passed to the view.
Replace the HttpPost
Delete
action method (named DeleteConfirmed
) with the following code, which performs the actual delete operation and catches any database update errors.
[HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { try { Student student = db.Students.Find(id); db.Students.Remove(student); db.SaveChanges(); } catch (DataException) { //Log the error (add a variable name after DataException) return RedirectToAction("Delete", new System.Web.Routing.RouteValueDictionary { { "id", id }, { "saveChangesError", true } }); } return RedirectToAction("Index"); }
This code retrieves the selected entity, then calls the Remove
method to set the entity's status to Deleted
. When SaveChanges
is called, a SQL DELETE
command is generated.
If improving performance in a high-volume application is a priority, you could avoid an unnecessary SQL query to retrieve the row by replacing the lines of code that call the Find
and Remove
methods with the following code:
Student studentToDelete = new Student() { StudentID = id }; db.Entry(studentToDelete).State = EntityState.Deleted;
This code instantiates a Student
entity using only the primary key value and then sets the entity state to Deleted
. That's all that the Entity Framework needs in order to delete the entity.
As noted, the HttpGet
Delete
method doesn't delete the data. Performing a delete operation in response to a GET request (or for that matter, performing an edit operation, create operation, or any other operation that changes data) creates a security risk. For more information, see ASP.NET MVC Tip #46 — Don't use Delete Links because they create Security Holes on Stephen Walther's blog.
In Views\Student\Delete.cshtml, add the following code between the h2
heading and the h3
heading:
<p class="error">@ViewBag.ErrorMessage</p>
Run the page by selecting the Students tab and clicking a Delete hyperlink:
Click Delete. The Index page is displayed without the deleted student. (You'll see an example of the error handling code in action in the Handling Concurrency tutorial later in this series.)
Ensuring that Database Connections Are Not Left Open
To make sure that database connections are properly closed and the resources they hold freed up, you should see to it that the context instance is disposed. That is why you will find a Dispose method at the end of the StudentController
class in StudentController.cs, as shown in the following example:
protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); }
The base Controller
class already implements the IDisposable
interface, so this code simply adds an override to the Dispose(bool)
method to explicitly dispose the context instance.
You now have a complete set of pages that perform simple CRUD operations for Student
entities. In the next tutorial you'll expand the functionality of the Index page by adding sorting and paging.
Links to other Entity Framework resources can be found at the end of the last tutorial in this series.
发表评论
-
C# WinForm程序如何与js交互
2012-07-15 22:28 2318一、建立网页 <html ... -
SQLITE FOR .NET4.0使用说明以及DLL
2012-06-28 22:07 1202SQLITE FOR .NET4.0使用说明以及DLL -
WinForm中TabControl的一些事件写法(C#)
2012-06-27 20:41 9877在TabControl控件中并没提供单个选项卡的Click事件 ... -
C# 通过字符串动态创建一个窗体
2012-06-27 20:27 1744private void button1_Click(obje ... -
vs2010 打包winform成EXE文件
2012-04-20 14:03 1643见附件 -
C#中DataGridView控件60招
2012-01-13 09:36 65571. DataGridView当前的单元格属性取得、变更 2 ... -
单击dataGridView某一行时将dataGridView当前选择行的某列值赋值给某个文本框
2012-01-13 09:19 2458SelectedRows和CurrentRow之间的区别 ... -
c# winform开发-datagridview开发
2012-01-13 09:18 1727datagridview 操作详解 目录: 1、 取得或 ... -
C# 中奇妙的函数. String Split 和 Join
2011-10-25 10:51 1110很多时候处理字符串数据,比如从文件中读取或者存入 - 我们可能 ... -
asp.net中web.config配置节点大全详解
2011-10-25 10:16 1373asp.net中web.config配置节点大全详解 2 ... -
Entity Framework in ASP.NET MVC Application (三)
2011-05-10 20:31 2467In the previous tutorial you im ... -
Entity Frame Work 4.1调用存储过程
2011-05-10 20:24 2134在这个问题上,琢磨了很久了。今天终于找到了调用的方法。 存储 ... -
entity-framework (code-first)实例开发(一)
2011-05-09 20:40 2751The Contoso University Web Appl ... -
使用ef4.1 的dbcontext进行数据库循环操作
2011-04-24 23:06 2263如果你想要调用一个类的方法进行循环操作:官方的例子: Dis ... -
使用EF 4.1的DbContext
2011-04-24 22:36 3641简述:EF4.1包括Code First和DbContext ... -
ADO.NET 访问存储过程
2011-04-24 22:15 1590ADO.NET 访问存储过程其实也比较简单,但是有些小细节部分 ... -
JAVA与.NET的相互调用——通过Web服务实现相互调用(附原代码)
2011-04-24 20:58 1287JAVA与.NET是现今世界竞争激烈的两大开发媒体,两者语言有 ... -
视图模式/视图->视图包
2011-04-24 20:16 1472ASP.NET MVC(自V1起)就支持一个带控制器和视图的V ... -
SkipRequestValidation] –> [AllowHtml]
2011-04-24 20:15 1437ASP.NET MVC内置了防止HTML和跨站脚本注入攻击的支 ... -
Log4net 详细说明
2011-04-12 22:29 2071在实际项目中我们经常 ...
相关推荐
1. **项目初始化**:创建一个新的ASP.NET MVC项目,并在项目中引入Entity Framework库。 2. **定义模型**:创建表示数据库实体的C#类。这些类包含属性,对应于数据库表的列。例如,一个`Student`类可能包含`Id`、`...
**ASP.NET MVC 应用程序与 Entity Framework** ASP.NET MVC(Model-View-Controller)是一种广泛使用的开源Web应用程序框架,由Microsoft开发。它基于模式驱动的设计,鼓励清晰的分离关注点,使开发者能够构建可...
Model, map, and access data effectively with Entity Framework Core 2, ...This book is for ASP.NET Core MVC 2 developers who want to use Entity Framework Core 2 as the data access layer in their projects.
在本项目中,数据访问层可能通过ADO.NET或者Entity Framework与数据库交互,获取或保存商品信息。 5. **数据库实现**:项目可能使用SQL Server或其他关系型数据库存储商品信息。数据库设计应遵循规范化原则,确保...
- 在Visual Studio 2008中,选择"文件" > "新建项目",然后选择"ASP.NET MVC Web Application"模板。 - 输入项目名称,例如"TaskList",然后确认创建。 - 如果出现创建单元测试项目的提示,可根据需求选择是否...
在本文中,我们将深入探讨如何使用AngularJS、ASP.NET MVC、Web API和Entity Framework(EF)构建一个完整的多层Single Page Application(SPA)。这个技术栈是现代Web开发中常用的一组工具,它们协同工作,可以提供...
ASP.NET MVC4与SQLite是一个强大的组合,用于构建高效、轻量级的Web应用程序。ASP.NET MVC4是一个基于模型-视图-控制器(MVC)设计模式的开源框架,它允许开发者构建可维护、可测试的Web应用。SQLite则是一个便携式...
本文将详细讲解如何利用.NET WPF(Windows Presentation Foundation)和ASP.NET MVC4技术构建一个夜猫商务会所的运营管理平台,提供一体化的解决方案。.NET WPF是微软开发的用于构建桌面应用程序的强大框架,而ASP...
You would also learn the fundamentals of Entity framework and on how to use the same in ASP.NET Core web applications. The book presents the fundamentals and philosophies of ASP.NET Core. Starting ...
开发者通常会使用ADO.NET Entity Framework或NHibernate这样的ORM(对象关系映射)工具进行数据访问。 通过这个示例源码,你可以学习到如何在ASP.NET MVC中创建控制器、视图和模型,理解路由机制,掌握如何与数据库...
在ASP.NET MVC中,我们通常使用T4模板来生成Entity Framework或其他ORM(对象关系映射)工具的数据访问层代码。这涉及到连接到数据库,创建模型类,以及生成用于CRUD操作的方法。 以下是如何使用T4模板连接到数据库...
5. **文件结构**:在提供的"MvcApplication10"项目中,我们可以看到典型的ASP.NET MVC项目结构,包括Controllers、Models、Views、App_Start、Content(存放CSS文件)、Scripts(存放JavaScript文件)等目录。...
在ASP.NET MVC中,这通常通过使用Entity Framework或ADO.NET来完成。创建一个Repository或者Service层,封装对数据库的操作,例如查询、分页等。假设我们有一个名为`Student`的数据模型,我们可以创建一个服务方法来...
【标题】"Web服务 ASP.NET MVC" 涉及的核心技术是ASP.NET框架下的MVC(Model-View-Controller)模式以及Web服务的创建。ASP.NET MVC是一个开源的Web应用程序框架,由微软开发,用于构建可测试、高性能的Web应用程序...
并内置于Visual Studio 2012,新版本ASP.NET MVC版本新增了手机模版、单页应用程序,Web API等模版,更新了一些 javascript 库,其中示例页面也使用了jquery的AJAX登录,并增加了OAuth认证/Entity Framework5的支持...