EF4 modification and Deletion

Source: Internet
Author: User

Recently, I made a DEMO of EntityFramework. When I first started to delete and modify data, I used to query the corresponding entity based on the ID, and then delete and update the object, it is found that the database has been queried multiple times. In particular, each attribute must be assigned a value to modify the modification, increasing the amount of code. Therefore, find another way out. The idea is probably like this: first obtain the object to be modified or deleted, and determine whether the context exists based on the EntityKey. If so, remove the object in the context. Then, attach the obtained object to the object context, and then update and save the database.

View Code

1 public void Update (Student entity)
2 {
3 entity. EntityKey = Session. CreateEntityKey ("Students", entity );
4 object s = new Student ();
5 if (Session. TryGetObjectByKey (entity. EntityKey, out s ))
6 {
7 Session. ObjectStateManager. ChangeObjectState (s, System. Data. EntityState. Deleted );
8 Session. Detach (s );
9}
10 Session. Attach (entity );
11 Session. ObjectStateManager. ChangeObjectState (entity, System. Data. EntityState. Modified );
12 Session. SaveChanges ();
13

Public void Delete (Student entity)
{
Entity. EntityKey = Session. CreateEntityKey ("Students", entity );
Object s = new Student ();
If (Session. TryGetObjectByKey (entity. EntityKey, out s ))
{
Session. Students. DeleteObject (Student) s );
}
Else
{
Session. AttachTo ("Students", entity );
Session. Students. DeleteObject (entity );
}
Session. SaveChanges ();
}

}

This code may have various vulnerabilities. Do you have any good methods to reply. Thank you, younger brother...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.