简体   繁体   中英

How to add an existing stored procedure to dbcontext with Entity Framework Core

I have an existing stored procedure that takes in several parameters. I'm trying to call it using EF Core.

Here is what I've got:

var results = _context.{this is where I need help}.FromSqlRaw( "mystoredproc  @param1 = {0}, @param2 = {1}, @param3 = {2}, @param4 = {3}", request.Date1, request.Date2, request.Date3, request.Date4).ToList();

My model looks like:

public class MyModel
{
    public int MyId { get; set; }
    public int Month { get; set; }
    public string Label { get; set; }
    // more properties but left out for space concerns
}

In my DbContext I've added:

public DbSet<MyModel> MyModel { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // not sure what to do here
}

I'm not sure what I need to do in the OnModelCreating .

You want the Database property, as in:

var results = _context.Database.FromSqlRaw( "mystoredproc  @param1 = {0}, @param2 = {1}, @param3 = {2}, @param4 = {3}", request.Date1, request.Date2, request.Date3, request.Date4).ToList();

See https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.database?view=efcore-3.1 and https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade?view=efcore-3.1 .

You call stored procedure this way as well

 var myIdParam = new SqlParameter("@MyId", myid);
 var monthParam = new SqlParameter("@Month", month);
 var labelParam = new SqlParameter("@Label", label);
 return await _context.MyModel.FromSqlRaw("EXEC mystoredproc @MyId,@Month,@Label ", new[] { myIdParam, monthParam,labelParam}).ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM