Reputation: 53
I have a class library project in .NET 6 where I am using EF Core. I am able to create tables using the code-first approach, but stuck on how to create stored procedures. I have seen a few articles on Google but it's showing using old EF 6 but not for EF Core.
Upvotes: 1
Views: 4303
Reputation: 1181
This is now possible in EF Core 7.0 with Stored procedure mapping:
modelBuilder.Entity<Person>()
.InsertUsingStoredProcedure("People_Insert", builder =>
{
builder.HasParameter(a => a.Name);
builder.HasResultColumn(a => a.Id);
})
.UpdateUsingStoredProcedure("People_Update", builder =>
{
builder.HasOriginalValueParameter(person => person.Id);
builder.HasOriginalValueParameter(person => person.Name);
builder.HasParameter(person => person.Name);
builder.HasRowsAffectedResultColumn();
})
.DeleteUsingStoredProcedure("People_Delete", builder =>
{
builder.HasOriginalValueParameter(person => person.Id);
builder.HasOriginalValueParameter(person => person.Name);
builder.HasRowsAffectedResultColumn();
});
Upvotes: -1
Reputation: 118937
There is no automatic way to create a stored procedure with EF Core, but the process to do it manually is quite simple.
First create a new migration as you would normally, it should be empty. Then edit the migration to manually create the procedure. For example:
public partial class MyNewStoredProcMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("CREATE PROC DoStuff....");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DROP PROC DoStuff");
}
}
Note that you may want to move the string for the procedure into a resource file to keep things tidy.
Upvotes: 5