1. Add Objects
Dbentity db = new dbentity (); Create an object entity, note that all properties need to be assigned (in addition to the auto-grow primary key), if not assigned, the database will be set to null (note whether it is nullable) var user = new user { Name = "Bomo", Age = +, Gender = "Male" }; Db. User.add (user); Db. SaveChanges ();
2. Delete the object, delete the primary key that only needs the object
Dbentity db = new dbentity (); Delete only need primary key, here Delete the primary key is 5 of the row var user = new User {Id = 5}; Attaches an entity to the object Manager in db. User.attach (user); Method one: db. User.remove (user); Method Two: Change the state of the current entity to delete //db. Entry (user). state = entitystate.deleted; Db. SaveChanges ();
3. Modify the Object
Method One:
Dbentity db = new dbentity (); The modification needs to assign a value to the primary key, note: All fields need to be assigned, the field without assignment is updated with NULL to the database var user = new user { Id = 5, Name = "Bomo", age = 21 , Gender = "male" }; Attaches an entity to the object Manager in db. User.attach (user); Change the state of the current entity to modified db. Entry (user). state = entitystate.modified; Db. SaveChanges ();
Method Two: Every time the method one needs to modify all the fields, inefficient, and troublesome, the following describes the modification of some fields
Dbentity db = new dbentity (); The modification needs to assign a value to the primary key, note: All fields need to be assigned, the field without assignment is updated with NULL to the database var user = new user { Id = 5, Name = "Bomo", age = 21 }; Attaches an entity to the object Manager in db. User.attach (user); Gets the state entity to user and can modify its state var setentry = ((iobjectcontextadapter) db). ObjectContext.ObjectStateManager.GetObjectStateEntry (user); Only the Name property of the entity and The Age attribute setentry.setmodifiedproperty ("name") are modified; Setentry.setmodifiedproperty ("Age"); Db. SaveChanges ();
4. Use transactions: It is very simple to use transactions, just put the required operations in TransactionScope, and finally commit
Dbentity db = new dbentity (); using (var scope = new TransactionScope ()) { //Perform multiple operations var user1 = new User { Name = "Bomo", age = Gender = "male" }; Db. User.add (user1); Db. SaveChanges (); var user2 = new User { Name = "Toroto", age = $, Gender = "female" }; Db. User.add (user2); Db. SaveChanges (); Commit TRANSACTION scope.complete (); }
5, Query: Query through LINQ query
Dbentity db = new dbentity (); Select the partial field var user = db. User.where (U = u.name = = "Bomo"). Select (U + = new {Id = u.id, Name = u.name, age = U.age}). FirstOrDefault (); Only functions that call FirstOrDefault, first, single, ToList, ToArray, and so on will execute queries against the database.
Entity Framework additions and deletions and transactional operations