EFCore使用SQL语句
执行非查询原生SQL
string msg = "内容";
await db.Database.ExecuteSqlInterpolatedAsync($"delete from comments where title={msg}");
实体相关的查询SQL ,
FromSqlInterpolated返回结果是IQueryable类型,在执行之前还可以对其进一步处理
string key = "%中%"; var list=db.Comments.FromSqlInterpolated($"select * from comments where content like {key}"); foreach (var item in list.take(10)) { Console.WriteLine($"{item.Id}:{item.Content}"); }
执行任意的SQL
var conn = db.Database.GetDbConnection(); if (conn.State != System.Data.ConnectionState.Open) { await conn.OpenAsync(); } using (var cmd = conn.CreateCommand()) { cmd.CommandText = "select id,标题 title from articles"; using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var id = reader.GetInt32(0); var title = reader.GetString(1); Console.WriteLine($"{id}:{title}"); } } }
使用Dapper
var conn = db.Database.GetDbConnection(); var list=conn.Query<OrgUnit>("select * from orgunits"); foreach (var item in list) { Console.WriteLine($"{item.Id}:{item.Name}"); }