1. Add objects
DbEntity db = new DbEntity(); // Create an object entity, note that all attributes need to be assigned here (except for the automatic growth of the primary key), if not assigned, the database will be set to NULL (note whether it is empty) var user = new User { Name = "bomo", Age = 21, Gender = "male" }; db.User.Add(user); db.SaveChanges();
2, delete the object, delete only the primary key of the object
DbEntity db = new DbEntity(); // Delete only needs the primary key, here delete the row with the primary key 5 var user = new User {Id = 5 }; // Attach the entity to the object manager db.User.Attach(user); // Method 1: db.User.Remove(user); // Method 2: Change the status 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 requires assignment to the primary key. Note: All fields need to be assigned here. Fields without assignments will be updated to the database with NULL var user = new User { Id = 5, Name = "bomo", Age = 21, Gender = "male" }; //将实体附加到对象管理器中 db.User.Attach(user); //把当前实体的状态改为Modified db.Entry(user).State = EntityState.Modified; db.SaveChanges();
方法二:方法一中每次都需要对所有字段进行修改,效率低,而且麻烦,下面介绍修改部分字段
DbEntity db = new DbEntity(); //修改需要对主键赋值,注意:这里需要对所有字段赋值,没有赋值的字段会用NULL更新到数据库 var user = new User { Id = 5, Name = "bomo", Age = 21 }; //将实体附加到对象管理器中 db.User.Attach(user); //获取到user的状态实体,可以修改其状态 var setEntry = ((IObjectContextAdapter) db).ObjectContext.ObjectStateManager.GetObjectStateEntry(user); //只修改实体的Name属性和Age属性 setEntry.SetModifiedProperty("Name"); setEntry.SetModifiedProperty("Age"); db.SaveChanges();
4、使用事务:使用事务很简单,只要把需要的操作放在 TransactionScope 中,最后提交
DbEntity db = new DbEntity(); using (var scope = new TransactionScope()) { //执行多个操作 var user1 = new User { Name = "bomo", Age = 21, Gender = "male" }; db.User.Add(user1); db.SaveChanges(); var user2 = new User { Name = "toroto", Age = 20, Gender = "female" }; db.User.Add(user2); db.SaveChanges(); // Submit the transaction scope.Complete(); }
5. Query: query through LinQ query
DbEntity db = new DbEntity(); // Select some fields var user = db.User.Where(u => u.Name == " bomo " ).Select(u => new {Id = u.Id, Name = u.Name, Age = u.Age}).FirstOrDefault(); // Only when FirstOrDefault, First, Single, ToList, ToArray and other functions are called, the query to the database will be executed