尽量使用EF的异步调用

await ctx.Students.ToListAsync()
await foreach (var s in ctx.Students.AsAsyncEnumerable())

FormattableString使用

    int a = 111;
    string world = "www";
    FormattableString s = @$"hello {world}, {a}";

    Console.WriteLine(s.Format);
    Console.WriteLine(string.Join(",", s.GetArguments()));


可以看到FormattableString并没有把所有的参数直接放入string中。

使用ExecuteSqlInterpolated实现更新操作

所以这样使用ExecuteSqlInterpolated(),不会导致sql注入攻击。
但是ExecuteSqlRaw()由于使用string参数,有可能导致sql注入攻击。

    using (MyDbContext ctx = new MyDbContext())
    {
        string name = "student_111";
        ctx.Database.ExecuteSqlInterpolated(@$"
insert into student(name)
values ({name})
");
    }

使用FromSqlInterpolated实现读取操作,并配合skip/take/include等使用

** 但是需要注意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();
    }

对于EF不能控制的SQL语句,可以直接使用ado.net core

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>("")