繁体   English   中英

如何使用 Entity Framework Core 将现有存储过程添加到 dbcontext

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

我有一个现有的存储过程,它接受多个参数。 我正在尝试使用 EF Core 调用它。

这是我所拥有的:

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();

我的模型看起来像:

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
}

在我的DbContext我添加了:

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

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

我不确定在OnModelCreating需要做什么。

您需要Database属性,如下所示:

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

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

您也可以这样调用存储过程

 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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