EF Core 2.0 如何使用SQL 存储过程

EF Core 2.0 how to use SQL stored procedure

我是 EF Core 2.0 的存储过程新手。

任何人都可以帮助我如何在我的 EF Core 2.0 代码优先方法中使用存储过程吗?

在我之前的项目中,我有一个 .edmx 模型文件,我使用的上下文如下:

public IEnumerable<UserResult> GetUserResults(Entities context)
{
    if (context == null) return new List<UserResult>();
    return context.spGetUsers().Where(u => u.IsDeleted == false);
}

上下文是:

public virtual ObjectResult<UserResult> spGetUsers()
{
    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<UserResult>("spGetUsers");
}

谢谢

您可以使用 FromSQL 方法:

var blogs = context.Blogs
    .FromSql("EXECUTE dbo.GetMostPopularBlogs")
    .ToList();

https://docs.microsoft.com/en-us/ef/core/querying/raw-sql

为别人节省一个小时左右...

ErikEJ 的回答很完美,但我还有一些额外的工作要做。

在反向代码第一次迁移(到具有存储过程的现有数据库)之后,我遇到了一个问题,即现有数据库上的存储过程没有return标准table(例如列表Blog),但不同的 class(例如 BlogTitleAndSummary 的列表)不在数据库中(因此迁移)。

这个 post 指出 Eriks post 的 return must be an entity type, which I was unsure of, but another 为我指明了正确的方向。

要使此场景正常工作:

我创建了 class 个 'BlogTitleAndSummary',将一个 属性 标记为 [key]

例如

public class BlogTitleAndSummary
{
    [Key]
    public int BlogId { get; set; }

    public string Title { get; set; }

    public string ShortSummary { get; set; }
}

然后,我将其作为 DbSet 添加到上下文中,例如

public partial class BloggingContext : DbContext
{
    public BloggingContext()
    {
    }

    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    {
    }

    // Might be best to move these to another partial class, so they don't get removed in any updates.
    public virtual DbSet<BlogTitleAndSummary> BlogTitleAndSummary { get; set; }

    // Standard Tables
    public virtual DbSet<Blog> Blog { get; set; }
    ...
}

这使我能够使用以下语法调用存储过程:

注意:我已根据下面的评论更新了此内容。使用 FromSql 方法中的参数。不要对这样的 .

使用字符串插值
using (var ctx = new BloggingContext())
{
var dbResults = ctx.BlogTitleAndSummary.FromSql("EXEC dbo.get_bloggingSummary @UserId={0}", userId).ToList();
}