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



我是带有存储过程的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://learn.microsoft.com/en-us/ef/core/querying/raw-sql

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

ErikEJ的答案非常有效,但我有一些额外的工作要先做。

在反向代码优先迁移(到具有存储过程的现有数据库)之后,我遇到了一个问题,即现有数据库上的存储过程不返回标准表(例如Blog列表),而是返回不在数据库中的不同类(例如BlogTitleAndSummary列表)(因此迁移)。

这篇文章说返回必须是实体类型,我不确定,但 Eriks 的另一篇帖子为我指出了正确的方向。

要使此方案正常工作,请执行以下操作:

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

例如

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

然后,我将其添加为上下文中的数据库集,例如

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 方法中的参数。不要对此类 sql 查询使用字符串内插。

using (var ctx = new BloggingContext())
{
var dbResults = ctx.BlogTitleAndSummary.FromSql("EXEC dbo.get_bloggingSummary @UserId={0}", userId).ToList();
}

最新更新