1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EFをSQLと併用するには

Posted at

EntityFrameworkを使いつつ、SQLを書くという都合のいいことができないかなぁと夢想しているとサポートされていたので学習録📓

FromSql()とLinqが併用可能
※EFCore7以前ならFromSqlInterpolated()をつかう

FromSql()の例

単純なselect

var blogs = context.Blogs
    .FromSql($"SELECT * FROM dbo.Blogs")
    .ToList();

Where

var param = "Taro"
var blogs = context.Blogs
    .FromSql($"SELECT * FROM dbo.Blogs WHERE USER = {param}")
    .ToList();

この書き方でSQLInjection大丈夫なんか、と思いますが自動でSQLParameterに展開してくれるそうです。すごいですね

EFのメソッドと組み合わせ

whereをLinqで指定

var param = "Taro"
var blogs = context.Blogs
    .FromSql($"SELECT * FROM dbo.Blogs")
+   .Where(x => x.User == param)
    .ToList();

上記の仕組みを使ってSQL内で関数を使い、フィルタ結果をプログラム内にて使用することでパフォーマンス改善に役立てないか目論見中…

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?