在EF Core里面如何使用以前EntityFramework的DbContext.Database.SqlQuery 自定義查詢


 問:


With Entity Framework Core removing dbData.Database.SqlQuery<SomeModel> I can't find a solution to build a raw SQL Query for my full-text search query that will return the tables data and also the rank.

The only method I've seen to build a raw SQL query in Entity Framework Core is via DbContext.Product.FromSql("SQL SCRIPT"); which isn't useful as I have no DbSet that will map the rank I return in the query.

 

答:


In EF Core you no longer can execute "free" raw sql. You are required to define a POCO class and a DbSet for that class. In your case you will need to define Rank:

var ranks = DbContext.Ranks
   .FromSql("SQL_SCRIPT OR STORED_PROCEDURE @p0,@p1,...etc", parameters)
   .AsNoTracking().ToList();

As it will be surely readonly it will be useful to include the .AsNoTracking() call.

 

意思就是EF Core不支持DbContext.Database.SqlQuery<SomeModel>這種自定義查詢了,請老老實實映射你的視圖或存儲過程查詢結果到一個EF Core的Entity上,然后使用DbSet的FromSql方法實現查詢結果的反序列化。。。

 

原文鏈接

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM