ASP.NET Core 6 Web API with Controller Entity Framework Core 6 Setup
-
Download EFCore in NuGet (Make sure EntityFrameworkCore are all in same version) a. Microsoft.EntityFrameworkCore b. Microsoft.EntityFrameworkCore.SqlServer c. Microsoft.EntityFrameworkCore.Tools
-
Create Model a. Set all necessary property b. All definition must same as ResultSet from DB
-
Create DbContext a. Make sure DBSet is declare public
-
Open Program.CS a. Add using statement code: using Microsoft.EntityFrameworkCore; b. Dependency Injection to builder.services, add before call for builder.Build(); code: services.AddDbContext(options =>options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
-
Add Connection string in appsetting.json "DefaultConnection" can be any name you like. code: (change value for server, db, etc) "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=BakeriesDb;Trusted_Connection=True;MultipleActiveResultSets=true" }
-
EFCore Done Setup
-
Start creating controllers a. Please check for source code for implementation b. ProcedureWithResultSet code: await _context.ProcedureReturn.FromSqlRaw(StoredProc).ToListAsync(); c. ProcedureWithOutReturn code await _context.Database.ExecuteSqlRawAsync(StoredProc,new SqlParameter("@Name",input.Name));
-
ProcedureWithResultSet; ProcedureWithOutReturn; sample Store Procedure run it in your DB;
CREATE PROCEDURE ProcedureWithResultSet @Id varchar(50) AS SELECT Id,Name,'' Description FROM YourTable WHERE Id = @Id; RETURN 0
CREATE PROCEDURE ProcedureWithOutReturn @Name varchar(50) AS insert into YourTable (Name) values (@Name); RETURN 0