0

What is the Alternate for SqlQuery in EF Core2.0 I dont want to create a model for executing the procedure

     var result =  _context.Database.SqlQuery<string>("TWS_config_MidOfficeSystems_Validate @mo,@ga,@pcc,@xmo",
                                   parameters: new SqlParameter[]
                                   {   new SqlParameter("@mo",lineData),
                                    new SqlParameter("@ga", gdsAccessId),
                                    new SqlParameter("@pcc", crsPCC),
                                    new SqlParameter("@xmo", bkMidOfficeCode),
                                   }).FirstOrDefaultAsync();
  • Duplicate: [Raw SQL Query without DbSet - Entity Framework Core](https://stackoverflow.com/questions/35631903/raw-sql-query-without-dbset-entity-framework-core) – Gert Arnold Mar 28 '20 at 12:40

1 Answers1

0

As EF Core tightly coupled, You have to create class with properties coming from stored procedure.

 public class ExampleClass
 {            
     public string Name { get; set; }
     public string Email { get; set; }            
 }

In ApplicationDbContext.cs add that class as DbQuery

 public DbQuery<ExampleClass> ExampleClassDbQuery { get; set; }

Implement Dependency Injection into your controller or services

private readonly ApplicationDbContext _db;


    public ExampleService(ApplicationDbContext applicationDbContext)
    {
        _db = applicationDbContext;  
    }

Then call stored procedure like this:

_db.ExampleClassDbQuery.FromSql("storedProcedureName", []parameters);

For more to know about running raw queries using FromSql please follow this Microsoft Docs

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rabby Hasan
  • 356
  • 4
  • 10