Muk*_*thi 9 stored-procedures entity-framework-core asp.net-core-2.0 entity-framework-core-migrations
我是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);
}
Run Code Online (Sandbox Code Playgroud)
上下文是:
public virtual ObjectResult<UserResult> spGetUsers()
{
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<UserResult>("spGetUsers");
}
Run Code Online (Sandbox Code Playgroud)
谢谢
Eri*_*kEJ 10
您可以使用FromSQL方法:
var blogs = context.Blogs
.FromSql("EXECUTE dbo.GetMostPopularBlogs")
.ToList();
Run Code Online (Sandbox Code Playgroud)
https://docs.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; }
}
Run Code Online (Sandbox Code Playgroud)
然后,我将其作为Context添加为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; }
...
}
Run Code Online (Sandbox Code Playgroud)
这使我能够使用以下语法来调用存储过程:
注意:我已更新以下注释以下。在FromSql方法中使用参数。不要将字符串插值用于此类sql查询。
using (var ctx = new BloggingContext())
{
var dbResults = ctx.BlogTitleAndSummary.FromSql("EXEC dbo.get_bloggingSummary @UserId={0}", userId).ToList();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15437 次 |
最近记录: |