Hello @Williamson, Stephen
Here is an example using EF Core 5 inserting a new record into a table and returning the new primary key. Full source in the following GitHub repository.
Table definition
Stored procedure
Insert stored procedure in SQL-Server database containing the table above.
CREATE PROCEDURE [dbo].[uspInsertCategory]
@CategoryName NVARCHAR(15),
@Description ntext,
@Identity INT OUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO dbo.Categories (CategoryName, Description) VALUES (@CategoryName, @Description);
SET @Identity = SCOPE_IDENTITY()
END
Code
Code to insert a new record. Pay attention to the second parameter which after the command is finished if successful contains the new primary key where the parameter is setup as Output directions.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using StoredProcedureInsertNewCategory.Context;
namespace StoredProcedureInsertNewCategory.Classes
{
public class Operations
{
/// <summary>
/// Insert new category
/// </summary>
/// <param name="categoryName">Category name required</param>
/// <param name="description">Category description</param>
public static void InsertCategory(string categoryName, string description)
{
using var context = new NorthWindContext();
try
{
var parameters = new[] {
new SqlParameter("@CategoryName", SqlDbType.NVarChar)
{
Direction = ParameterDirection.Input,
Value = categoryName
},
new SqlParameter("@Description", SqlDbType.NText)
{
Direction = ParameterDirection.Input,
Value = description
},
new SqlParameter("@Identity", SqlDbType.Int)
{
Direction = ParameterDirection.Output,
Value = 0
}
};
context.Database.ExecuteSqlRaw(
"exec uspInsertCategory @CategoryName,@Description,@Identity out", parameters:
parameters);
var newPrimaryKey = Convert.ToInt32(parameters[2].Value);
Debug.WriteLine(newPrimaryKey.ToString());
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
This is the model for above
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
#nullable disable
namespace StoredProcedureInsertNewCategory.Models
{
public partial class Category
{
/// <summary>
/// Primary key
/// </summary>
[Required]
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public byte[] Picture { get; set; }
}
}