1 ActionUrl c = new ActionUrl() { ActionName="test", RequestUrl="/123/123", SubTime=DateTime.Now }; 2 //增 3 using (EntityContext db = new EntityContext()) 4 { 5 6 /*方法1*/ 7 db.ActionUrls.Add(c); 8 db.SaveChanges(); 9 /*方法2*/ 10 db.Set<ActionUrl>().Attach(c); 11 db.Entry<ActionUrl>(c).State = EntityState.Added; 12 db.SaveChanges(); 13 //return c; 14 /*方法3*/ 15 //EF4.0的写法 16 //db.CreateObjectSet<T>().AddObject(entity); 17 18 } 19 //查 20 using (EntityContext db = new EntityContext()) 21 { 22 c = db.ActionUrls.Where(t => t.ActionName == "test").FirstOrDefault(); 23 } 24 //改 25 using (EntityContext db = new EntityContext()) 26 { 27 /*方法1*/ 28 c.ActionName = "test001"; 29 db.ActionUrls.Attach(c); 30 db.Entry<ActionUrl>(c).State = EntityState.Modified; 31 db.SaveChanges(); 32 /*方法2*/ 33 c.ActionName = "test002"; 34 db.SaveChanges(); 35 //return db.SaveChanges() > 0; 36 /*方法3*/ 37 //EF4.0的写法 38 //db.CreateObjectSet<T>().Addach(entity); 39 //db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); 40 } 41 //删 42 using (EntityContext db = new EntityContext()) 43 { 44 /*方法1*/ 45 //此处删除的对象不能是自己定义出来的对象,只能是数据库查询出来的对象 46 c = db.ActionUrls.Where(t => t.ActionName == "test").FirstOrDefault(); 47 db.ActionUrls.Remove(c); 48 db.SaveChanges(); 49 /*方法2*/ 50 //c = db.ActionUrls.Where(t => t.ActionName == "test").FirstOrDefault(); 51 db.Set<ActionUrl>().Attach(c); 52 db.Entry<ActionUrl>(c).State = EntityState.Deleted; 53 db.SaveChanges(); 54 //return db.SaveChanges() > 0; 55 /*方法3*/ 56 //EF4.0的写法 57 //db.CreateObjectSet<T>().Addach(entity); 58 //db.ObjectStateManager.ChangeObjectState(entity, EntityState.Deleted); 59 } 60 61 //存储过程和sql语句 62 EntityContext dbsql = new EntityContext(); 63 SqlParameter[] parameters = new SqlParameter[]{ 64 new SqlParameter("@name",SqlDbType.NVarChar) 65 }; 66 parameters[0].Value = "test"; 67 68 //执行strSql/procSql 69 //返回受影响的行数 70 int i = dbsql.Database.ExecuteSqlCommand("exec getActionUrlId @name", parameters); 71 72 List<ActionUrl> dd01 = dbsql.Database.SqlQuery(typeof(ActionUrl), "exec getActionUrlId @name", parameters).Cast<ActionUrl>().ToList(); 73 //执行strSql/procSql 74 //返回数据的集合 75 List<ActionUrl> dd02 = dbsql.Database.SqlQuery<ActionUrl>("exec getActionUrlId @name", parameters).ToList();//返回查询到的实体集合
大致的增删查改和存储过程,执行sql语句和执行存储过程差不多。只有删除比较特殊!
时间: 2024-10-14 07:52:06