In the previous article we have created the EF4.1 code first example with a database and initialized some data here today write base additions and deletions and changes to the life cycle of persistent objects
Learn the original version of the first to put on the good work ~ ~
I. Create a detail page
First we'll add a detailed page to the controller
Since this article describes the changes to the persistence object declaration cycle, let's look at what the states are
There's a whole EF in this V life state type actually look at the name we can guess a Sanlai ~ ~ Free unchanged The newly added deleted modified but how the change can
We practice and confirm in the code that follows
Public ActionResult Details (int id)
{
Student student= db. Students.find (ID);
EntityState Statebefore = db. Entry (student). State; The state obtained by find is unchanged
Return View (student);
}
By debugging we can see that the status obtained by find is unchanged unchanged ~ ~
We used the DB in this. Entry () method This method is very good not only to see the state can also be traced to OriginalValue (original value), CurrentValue (current value) and Databasevalue (database value)
See the garden has already introduced this and write very good ~ ~ Here directly connect to everyone to see the article connection
Then go back to our project-now start adding views
View Code
In this we show not only the student's details but also the courses and grades that the student has chosen.
Because our student entity has navigation properties Enrollments 这里面 遍历每一个
Enrollments
toEnrollment 来得到分数 由于我们的
Enrollment 实体 包含了课程实体的导航属性 所以可以得到
课程的名字
This involves loading the load of multi-relational data for read-related properties such as lazy loading this is not the focus of our discussion this will be discussed in the fifth section will be loaded in the form of SQL statements and so clear the peace of mind ~ ~
I'm not going to talk about it right here. Start the following Create page
Two. Create an Add page
The first step is still to add the controller under the method of this inside the method to remember is HttpPost
Create 不加post 就是get的方式 是直接访问页面时用的 post提交时用
其次 我们依然来看下这次生命周期状态的改变
[HttpPost]
Public actionresult Create (Student Student)
{
Try
{
//todo:add insert logic here
if (modelstate.isvalid)
{
EntityState Statebefore = db. Entry (student). State; Detached
Db. Students.add (student);
EntityState stateadd = db. Entry (student). State; Added
Db. SaveChanges ();
EntityState stateafter = db. Entry (student). State;//unchanged
Return redirecttoaction ("Index");
}
}
Catch
{
Modelstate.addmodelerror ("", "unable to save C Hanges. Try again, and if the problem persists see your system administrator. ");
}
return View (student);
}
Let's start with the MVC problem. Here we can change the parameters directly to create (Student Student) can also use FormCollection to get a value but the first way is recommended ~ ~
This is the principle of routing or parameter, will be automatically assigned to the corresponding property of the object to do this work is to achieve the Imodelbinder interface
Interested can go to Google next ~ ~ here to talk about EF mvc things Incidentally ~
Back to the example we can see the change of life cycle Detached--->added---->unchanged
Add a View
View Code
Here we choose to turn on Verify that MVC validation verifies the client re-authenticate the server and we can verify that there is a null maximum length for the minimum length format comparison and so on
Here we only need to add attributes such as attribute MaxLength on the entity
Here I have all the features you can add to the collection and introduction you can see this connection article-----dataannotation verification
Then run the discovery when adding data does not meet the requirements will be the JS verification prompt error OK add to Here
Three. Create an edit page
Public ActionResult Edit (int id)
{
Student Student = db. Students.find (ID);
Return View (student);
}
//
POST:/STUDENT/EDIT/5
[HttpPost]
Public ActionResult Edit (Student Student)
{
Todo:add Update logic here
if (modelstate.isvalid)
{
EntityState Statebefore = db. Entry (student). State;
Db. Entry (student). state = entitystate.modified;
int i= db. SaveChanges ();
EntityState stateafter= db. Entry (student). State;
Return redirecttoaction ("Index");
}
Return View (student);
}
Updates in EF are implemented by changing the state to entitystate.modified and then saving for the update operation.
We can see the change of life cycle Detached--->modified---->unchanged
Add a View
View Code
Four. Create a delete page
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));
}
//
POST:/STUDENT/DELETE/5
[Httppost,actionname ("Delete")]
Public ActionResult deleteconfirmed (int id)
{
Try
{
Todo:add Delete logic here
Student Student = db. Students.find (ID);
EntityState Statebefore = db. Entry (student). State; Unchange status
Db. Students.remove (student);
EntityState stateafter = db. Entry (student). state;//deleted status
Db. SaveChanges ();
EntityState STATEAOK = db. Entry (student). state;//detached status
Return redirecttoaction ("Index");
}
Catch
{
return View ();
}
}
View Code
That's how it's done. It's a method of the original blog, but I think it's unreasonable.
Click Delete and skip to the dedicated delete page and then jump back here. We use Ajax to transform the deletion to reduce the interaction of the page-hopping and so on to improve efficiency (the main point is to write MVC application ~ ~)
Five. Ajax Retrofit Delete
I'm here to use jquery Ajax with the habit of ~ ~
The method of reforming the controller first
The main thing is to add if (Request.isajaxrequest ()) to determine whether it is Ajax and then change the return type to Content return-1 to modify the failure code as follows
View Code
Then modify the View section
First, replace the original deletion with this sentence.
<a name= "Delete" stuid= "@item. StudentID ">Delete</a>
Then refer to jquery and then implement Delete ~ ~
$ (function () {
$ ("[name= ' Delete ']"). Click (
function () {
if (Confirm ("OK to delete this record?"). ")) {
var Stuid = $ (this). attr ("Stuid");
var tr = $ (this). Parent (). parent ();
$.post ("student/delete/", {Id:stuid}, function (data) {
if (data = = "-1") {
Alert ("Delete failed");
}
else {
$ (TR). Remove ();
Alert ("Delete succeeded");
}
});
}
}
);
});
OK, transformation success ~ ~
Six. Ensure timely release of database resources
In the original text in the most want to put Controller类继承
IDisposable接口 以确保资源的即使释放 这里我理解的还不是很深刻有兴趣的可以看下原文 但我把代码贴出来
protected override void Dispose (bool disposing)
{
Db. Dispose ();
Base. Dispose (disposing);
}
七.总结
好了,简单的增删改查结束了 依然是没有多大难度的文章 新手可以看下 学习下EF的使用
这里面主要讲了 基本的CRUD和 这里面持久属性的状态的变化 并在后面用ajax重新实现了次删除
明天写
Sort Brush Select paging----(Here I'm using homemade ScottGu-based pagedlist<t> classes and related methods for perfect paging--mvcpager)
is also relatively simple but at least more close to the actual project ~ ~
Reprint please keep the original link thank you ~ ~ Original Address
mvc3+ef4.1 Learning Series (ii) additions and deletions of-------basis and life cycle changes of persistent objects