EF版本:6.0.0
EF对大量数据或多表连接一次操作耗时较大,或要求响应时间尽可能小,因此采用EF框架执行SQL语句的方案
1DbContext.Database
这个类包含了大量的操作方法,见截图:
查询方法举例:
using (CustomDbContext db = new CustomDbContext()) { string sql = "SELECT * FROM collections LEFT JOIN collectionusers ON collections.`Id`=collectionusers.`Collection_Id`"; var task = db.Database.SqlQuery<Collection>(sql).ToListAsync(); task.Wait(); var r = task.Result; }
删除方法举例:
using (CustomDbContext db = new CustomDbContext()) { string sql = "delete from collectionusers where Id=@id"; var num = db.Database.ExecuteSqlCommand(sql, new MySqlParameter("@id", 322)); }
注意操作Mysql数据库,一定要是有MySqlParameter而不能使用SqlParameter,使用SqlParameter会抛出异常:Only MySqlParameter objects may be stored
更新方法举例:
using (CustomDbContext db = new CustomDbContext()) { string sql = "update collectionusers set InsertTime=@time where Id=@id"; var num = db.Database.ExecuteSqlCommand(sql, new MySqlParameter("@time", DateTime.Now),new MySqlParameter("@id", 323)); }
插入方法举例:
using (CustomDbContext db = new CustomDbContext()) { db.Database.ExecuteSqlCommand("SET SQL_SAFE_UPDATES=0");//不启用更新安全模式 db.Database.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS=0");//取消外键约束 string sql = "INSERT INTO collectionusers (`InsertTime`, `Collection_Id`, `User_Id`)VALUES(@insertTime,@cid, @uid)"; var num = db.Database.ExecuteSqlCommand(sql, new MySqlParameter("@insertTime", DateTime.Now), new MySqlParameter("@cid", 11), new MySqlParameter("@uid",22)); }
事务操作举例:
CustomDbContext db = null; DbContextTransaction tran = null; try { db = new CustomDbContext(); tran = db.Database.BeginTransaction(); db.Database.ExecuteSqlCommand("SET SQL_SAFE_UPDATES=0");//不启用更新安全模式 db.Database.ExecuteSqlCommand("SET FOREIGN_KEY_CHECKS=0");//取消外键约束 string sql = "INSERT INTO collectionusers (`InsertTime`, `Collection_Id`, `User_Id`)VALUES(@insertTime,@cid, @uid)"; var num = db.Database.ExecuteSqlCommand(sql, new MySqlParameter("@insertTime", DateTime.Now), new MySqlParameter("@cid", 11), new MySqlParameter("@uid", 22)); tran.Commit(); } catch { tran.Rollback(); } finally { if (db != null) db.Dispose(); if (tran != null) tran.Dispose(); }
-----------------------------------------------------------------------------------------
转载与引用请注明出处。