ASP.NET Core和EF Core 1.1 - 使用存储过程的Diplay数据

时间:2017-03-29 07:42:53

标签: asp.net-core entity-framework-core

我的查询有问题。我想在视图上显示结果。

[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index()
{
    return View(await _Context.Employee
                              .FromSql("EXEC sp_GetLoanDetails")
                              .ToArrayAsync());
}

以下是我要查看的项目列表:

public class StoredProcRow
{
    [Key]
    public int empID { get; set; }
    public string empFullName { get; set; }
    public double EducationalLoan { get; set; }
    public double PettyCash { get; set; }
    public double BusinessLoan { get; set; }
    public double ApplianceLoan { get; set; }
    public double EmergencyLoan { get; set; }
    public double AllPurposeLoan { get; set; }
    public double KAPUSOIILoan { get; set; }
    public double FiestaLoan { get; set; }
    public double SalaryLoan { get; set; }
    public double Pledge { get; set; }
    public double PagIbigLoan { get; set; }
    public double SSSLoan { get; set; }
    public double AllAroundLoan { get; set; }
    public double Total { get; set; }
}

注意:这些实体名称与sp_GetLoanDetails

中列名称上的实体相同

这是否可以在EF Core 1.1上实现?或者我是否需要返回手动ADO.NET代码?

谢谢!

2 个答案:

答案 0 :(得分:8)

虽然对于存储过程的支持并不完全存在于Entity Framework Core yet,但您仍然可以使用FromSql来使用存储过程。

为此,数据库上下文需要知道要从存储过程映射到的实体。不幸的是,现在唯一的方法是将其实际定义为数据库上下文中的实体:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<StoredProcRow>(entity =>
    {
        // …
    });
}

然后,您可以通过在该实体的集合上运行FromSql方法来使用存储过程:

public virtual IQueryable<StoredProcRow> GetLoanDetails()
{
    return Set<StoredProcRow>().FromSql("[sp_GetLoanDetails]").AsNoTracking();
}

请注意,我在这里使用AsNoTracking来避免数据上下文跟踪来自存储过程的实体的更改(因为您无论如何都无法更新它们)。此外,我在方法中使用Set<T>()以避免必须将类型公开为数据库上下文中的成员,因为无论如何都不能使用没有存储过程的集合。

顺便说一下。您传递给EXEC的sql语句中不需要(不确定是否可行)FromSql。只需传递存储过程名称及其任何参数,例如:

Set<MyEntity>().FromSql("[SomeStoredProcedure]");
Set<MyEntity>().FromSql("[SProcWithOneArgument] @Arg = {0}");
Set<MyEntity>().FromSql("[SProcWithTwoArguments] @Arg1 = {0}, Arg2 = {1}");

答案 1 :(得分:0)

从NuGet添加System.Data.Common和System.Data.SqlClient。这些允许运行ADO.NET命令,即存储过程。

https://forums.asp.net/post/6061777.aspx

相关问题