How to use EF .SqlQuery expression in EFCore?

.net .net-core c# entity-framework entity-framework-core

Question

I'm refactoring a code and I have this question.

public class MovimentoManualListRepository : RepositoryBase<MovimentoManualList>, IMovimentoManualListRepository
{
    ConsultarContext _context;
    public MovimentoManualListRepository(ConsultarContext context) : base(context)
    {
        _context = context;
    }

    public List<MovimentoManualList> Listar()
    {
        return _context.Database
            .SqlQuery<MovimentoManualList>("ListarMovimentacao")
            .ToList();
    }
}

I get an error:

Severity Code Description Project File Line Suppression State Error CS1061 'DatabaseFacade' does not contain a definition for 'SqlQuery' and no accessible extension method 'SqlQuery' accepting a first argument of type 'DatabaseFacade' could be found (are you missing a using directive or an assembly reference?)

1
0
10/20/2019 6:20:11 AM

Accepted Answer

Do you mean FromSqlRaw.?

Basic raw SQL queries

You can use the FromSqlRaw extension method to begin a LINQ query based on > a raw SQL query. FromSqlRaw can only be used on query roots, that is directly on the DbSet<>.

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

The following executes a stored procedure

var blogs = context.Blogs
    .FromSqlRaw("EXECUTE dbo.GetMostPopularBlogs")
    .ToList();

Please note that:

  • it can be mixed and matched it with Linq queries
  • there are limitations

Please see Raw SQL Queries.

1
10/20/2019 6:20:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow