【问题标题】:Execute procedure and return data from different tables in Net 5在 Net 5 中执行过程并从不同的表返回数据
【发布时间】:2022-01-01 17:41:58
【问题描述】:

我正在尝试使用 NET 5 和 Entity Framework Core 5 在 RESTful API 中运行一个过程,该过程从不同的表返回数据。

我的问题是我不知道如何在 DetailsClientsDto 类中执行稍后返回数据的过程。

尝试通过以下方式运行该过程,但没有成功:

var result = await _context.Database.SqlQuery<DetailsClientsDto>("EXEC [dbo].[SPROC_DETAILS] @ID_USER", sqlParameters);

var result = await _context.SqlQuery<DetailsClientsDto>("EXEC [dbo].[SPROC_DETAILS] @ID_USER", sqlParameters);

错误:

DataBase facade does not contain a definition for SqlQuery. Is there a using directive missing?

我使用的方法是:

private readonly MarketContext _context;
public ClientsRepository(MarketContext context) : base(context)
{
    _context = context;
}

public async Task<DetailsClientsDto> GetDetailsRepository(SearchDetailsDto details)
{
    var sqlParameters = new[]
    {
        new SqlParameter
        {
            ParameterName = "ID_USER",
            Value = details.IdUser,
            SqlDbType = SqlDbType.Int,
        },
        new SqlParameter
        {
            ParameterName = "ID_CLIENT",
            Value = detalles.IdClient,
            SqlDbType = SqlDbType.Int,
            IsNullable=true
        },
    };
    
    return await Task.Run(async () =>
    {
        var result = await _context.Database.SqlQuery<DetailsClientsDto>("EXEC [dbo].[SPROC_DETAILS] @ID_USER", sqlParameters);

        return result;
    }); 
}

public class DetailsClientsDto
{
    public int IdUser { get; set; }
    public int IdClient { get; set; }
    public string User { get; set; }
    public string Adress { get; set; }
    public string Car { get; set; }
    public string Color { get; set; }
}

请您告诉我应该如何执行程序并返回数据,谢谢。

【问题讨论】:

  • EF Core 没有SqlQuery 扩展。
  • 感谢@SvyatoslavDanyliv。在没有 EFC 的情况下,执行过程并从多个表返回值的正确方法是什么?
  • 我建议安装 Dapper,否则您必须使用 EFCore 模型注册 DTO 实体。
  • 检查this answer

标签: c# stored-procedures entity-framework-core .net-5


【解决方案1】:

这是一个例子:

// Load this namespace to use SqlParameter
using Microsoft.Data.SqlClient;

//.. or use db.Set<DetailsClientsDto>()
var result = await db.DetailsClientsDto 
  .FromSqlRaw("EXEC [dbo].[SPROC_DETAILS] @idUser, @anotherParam", 
    new SqlParameter("idUser", value1),     
    new SqlParameter("anotherParam", value2))
  .AsNoTracking()
  .ToListAsync()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2021-06-26
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    相关资源
    最近更新 更多