await ctx.Students.ToListAsync()
await foreach (var s in ctx.Students.AsAsyncEnumerable())
int a = 111; string world = "www"; FormattableString s = @$"hello {world}, {a}"; Console.WriteLine(s.Format); Console.WriteLine(string.Join(",", s.GetArguments()));
可以看到FormattableString并没有把所有的参数直接放入string中。
所以这样使用ExecuteSqlInterpolated(),不会导致sql注入攻击。
但是ExecuteSqlRaw()由于使用string参数,有可能导致sql注入攻击。
using (MyDbContext ctx = new MyDbContext()) { string name = "student_111"; ctx.Database.ExecuteSqlInterpolated(@$" insert into student(name) values ({name}) "); }
** 但是需要注意FromSqlInterpolated不支持Join操作。**
using (MyDbContext ctx = new MyDbContext()) { string pattern = "%3%"; IQueryable<Student> students = ctx.Students.FromSqlInterpolated(@$" select * from student where name like {pattern} "); students.Skip(2).Take(5).ToArray(); }
var conn = ctx.database.getdbconnection() using (var cmd = conn.CreateCommand()) { cmd.CommandText = "select price, count(*) from article group by price"; using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { } } }
或者使用dapper
dapper会把结果反射到GroupArticleByPrice对象。
ctx.Database.GetDbConnection().Query<GroupArticleByPrice>("")