How to call stored procedure procedure using entity framework core?
From your code and description, it seems that you have already create the stored procedure on the database (follow the database-first approach). If that is the case, you can refer to the following sample and steps:
1.Create a stored procedure sp-GetBookAuthors: the Books and Authors are configured many-to many relationships using EF core:
2.Based on the stored procedure return data to create a view model:
public class BookAuthorViewModel
{
public int BookId { get; set; }
public string BookName { get; set; }
public string AuthorName { get; set; }
}
3.Add the DbSet in the ApplicationDbContext:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<BookAuthor> BookAuthors { get; set; }
public DbSet<BookAuthorViewModel> BookAuthorViewModel { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<BookAuthor>()
.HasKey(bc => new { bc.BookId, bc.AuthorId });
modelBuilder.Entity<BookAuthor>()
.HasOne(bc => bc.Book)
.WithMany(b => b.BookAuthors)
.HasForeignKey(bc => bc.BookId);
modelBuilder.Entity<BookAuthor>()
.HasOne(bc => bc.Author)
.WithMany(c => c.BookAuthors)
.HasForeignKey(bc => bc.AuthorId);
modelBuilder.Entity<BookAuthorViewModel>().HasNoKey();
}
}
4.Enable migration for the BookAuthorViewModel, it will generate a BookAuthorViewModel in the database
add-migration addbookauthorviewmodel
update-database
5.Then, in the Controller, we can call the stored procedure using the FromSql
method:
public class BookController : Controller
{
private readonly ApplicationDbContext _dbContext;
public BookController(ApplicationDbContext applicationDbContext) {
_dbContext=applicationDbContext;
}
public IActionResult Index()
{
var result = _dbContext.BookAuthorViewModel.FromSql($"execute sp_GetBookAuthors @bookname = 'Book A'").ToList();
return View();
}
}
The result as below:
Reference: Working with Stored Procedure in Entity Framework Core and CRUD Operation Using Entity Framework Core And Stored Procedure In .NET Core 6 Web API
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion