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...