Using SqlQuery to get IQueryable

前端 未结 2 1786
耶瑟儿~
耶瑟儿~ 2021-01-04 01:33

Is there something that can return IQueryablefor a dynamic sql query in Entity Framework 6?

This is what I am using now but it is pulling all the record

2条回答
  •  时光取名叫无心
    2021-01-04 02:01

    I know this question is about EF6 but in case somebody else stumbles upon this question but interested in EFCore, this is actually possible there.

    • Source from Docs

    Most simple example:

    var user = new SqlParameter("user", "johndoe");
    
    var blogs = context.Blogs
        .FromSqlRaw("EXECUTE dbo.GetMostPopularBlogsForUser @user", user)
        .ToList();
    

    Parameters:

    var user = new SqlParameter("user", "johndoe");
    
    var blogs = context.Blogs
        .FromSqlRaw("EXECUTE dbo.GetMostPopularBlogs @filterByUser=@user", user)
        .ToList();
    

    More complex example (this is more specifically what this question is asking for):

    var searchTerm = ".NET";
    
    var blogs = context.Blogs
        .FromSqlInterpolated($"SELECT * FROM dbo.SearchBlogs({searchTerm})")
        .Where(b => b.Rating > 3)
        .OrderByDescending(b => b.Rating)
        .ToList();
    

    Resulting query for more complex example:

    SELECT [b].[Id], [b].[Name], [b].[Rating]
            FROM (
                SELECT * FROM dbo.SearchBlogs(@p0)
            ) AS b
            WHERE b."Rating" > 3
            ORDER BY b."Rating" DESC
    

    A few notes about this method:

    • You effectively have to do a SELECT * to make sure all columns are returned from the table.
    • Joins to pull back additional data don't work, but Include does in normal SQL queries (not necessarily stored proc/function calls).
    • Often times your raw Sql will be put into a subquery. So make sure it's valid for such things (i.e. semicolons, order bys, hints, etc. can cause problems).

提交回复
热议问题