{"id":104053,"date":"2024-01-23T12:18:03","date_gmt":"2024-01-23T11:18:03","guid":{"rendered":"https:\/\/code-maze.com\/?p=104053"},"modified":"2024-01-31T15:52:31","modified_gmt":"2024-01-31T14:52:31","slug":"aspnetcore-using-mariadb-with-web-api","status":"publish","type":"post","link":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/","title":{"rendered":"Using MariaDB With ASP.NET Core Web API"},"content":{"rendered":"<p>In this article, we will discuss how to use a MariaDB database with an ASP.NET Core Web API.<\/p>\n<p>First, we will discuss what MariaDB is and how we include it in our application. Then, we will use the Entity Framework Core library to create a mapping between our Web API models and our MariaDB database. After that, we&#8217;ll implement methods for creating, reading, updating, and deleting data from our MariaDB database. Finally, we will test our Web API and its MariaDB integration using Postman.<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/aspnetcore-webapi\/UsingMariaDBWithASPNETCoreWebAPI\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s dive in!<\/p>\n<h2><a id=\"H2\"><\/a>What is MariaDB?<\/h2>\n<p><strong>MariaDB is an open-source fork of the MySQL relational database management system (RDBMS)<\/strong>. It is currently actively maintained by the open-source community, led by many of the original developers of the MySQL database. In comparison to MySQL, MariaDB offers additional features, such as <a href=\"https:\/\/mariadb.com\/kb\/en\/galera-cluster\/\" target=\"_blank\" rel=\"nofollow noopener\">Galera<\/a>, <a href=\"https:\/\/mariadb.com\/kb\/en\/sequences\/\" target=\"_blank\" rel=\"nofollow noopener\">Sequences<\/a>, and the <a href=\"https:\/\/mariadb.com\/kb\/en\/uuid-data-type\/\" target=\"_blank\" rel=\"nofollow noopener\">UUID data type<\/a>. Furthermore, MariaDB provides extra storage engines like <a href=\"https:\/\/mariadb.com\/kb\/en\/columnstore\/\" target=\"_blank\" rel=\"nofollow noopener\">ColumnStore<\/a>, <a href=\"https:\/\/mariadb.com\/kb\/en\/myrocks\/\" target=\"_blank\" rel=\"nofollow noopener\">MyRocks<\/a>, and <a href=\"https:\/\/mariadb.com\/kb\/en\/aria\/\" target=\"_blank\" rel=\"nofollow noopener\">Aria<\/a>.<\/p>\n<p>Now that we know what MariaDB is, let\u2019s see how to download, install, and use it.<\/p>\n<h2><a id=\"H2\"><\/a>Preparation of MariaDB and ASP.NET Core App<\/h2>\n<p>First, let&#8217;s download MariaDB from the <a href=\"https:\/\/mariadb.org\/download\/\" target=\"_blank\" rel=\"nofollow noopener\">MariaDB download page<\/a>. Next, we install it with the preselected default options on the installation menu. <strong>We need to make a note of the root user password we set during the installation.<\/strong><\/p>\n<p><strong>It&#8217;s important to mention that the installation package includes the HeidiSQL app, a free GUI client for interacting with the MariaDB server<\/strong>. We can use this app to explore the databases we create.<\/p>\n<p>Next up, let&#8217;s create an ASP.NET Core Web API project named <code>UsingMariaDBWithASPNETCoreWebAPI<\/code>:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">dotnet new webapi --name UsingMariaDBWithASPNETCoreWebAPI<\/code><\/p>\n<p>To learn how to do this from Visual Studio, please visit our guide on <a href=\"https:\/\/code-maze.com\/net-core-web-development-part2\/#creatingNewProject\" target=\"_blank\" rel=\"noopener\">creating and configuring a new ASP.NET Core Web API project<\/a>.<\/p>\n<h3><a id=\"H3\"><\/a>Setting Up the Entity Framework Core Library to Connect MariaDB with ASP.NET Core APP<\/h3>\n<p><a href=\"https:\/\/code-maze.com\/entity-framework-core-series\/\" target=\"_blank\" rel=\"noopener\">Entity Framework (EF) Core<\/a> is a library that we can utilize to access our database from our web API. When we use the EF Core library, we can choose to build our application using either the <a href=\"https:\/\/code-maze.com\/asp-net-core-web-api-with-ef-core-db-first-approach\/\" target=\"_blank\" rel=\"noopener\">Database-First approach<\/a> or the <a href=\"https:\/\/code-maze.com\/net-core-web-api-ef-core-code-first\/\" target=\"_blank\" rel=\"noopener\">Code-First approach<\/a>.<\/p>\n<p>In the Database-First approach, we design our database first and then use EF Core to generate the tables and the context. In the Code-First approach,\u00a0we create our models and context first, then we use EF Core to create the database schema and possibly add seed data to it. Here, we will use the Code-First approach.<\/p>\n<p>That said, let\u2019s now install the EF Core package from the operating system command line:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet add package Microsoft.EntityFrameworkCore<\/code><\/p>\n<p>As the next step, let&#8217;s install the <a href=\"https:\/\/www.nuget.org\/packages\/Pomelo.EntityFrameworkCore.MySql\/8.0.0-beta.2\" target=\"_blank\" rel=\"nofollow noopener\">Pomelo.EntityFrameworkCore.MySql<\/a> database provider:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet add package Pomelo.EntityFrameworkCore.MySql -v 8.0.0-beta.2<\/code><\/p>\n<p>This NuGet package is the EF Core database provider for MariaDB and other MySQL-compatible databases.<\/p>\n<p>We utilize the version <code>-v 8.0.0-beta.2<\/code> modifier to specify the version of the provider. Using lower versions of this provider with version 8.0.0 of the <code>Microsoft.EntityFrameworkCore.Tools<\/code> package will cause an exception when we want to add our migrations.<\/p>\n<h3><a id=\"H3\"><\/a>Creating the Model<\/h3>\n<p>Now, let&#8217;s create a <code>Models<\/code> folder in our project&#8217;s base directory. In this folder, let&#8217;s define our model:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Student\r\n{\r\n    public int Id { get; set; }\r\n    public string? FirstName { get; set; }\r\n    public string? LastName { get; set; }\r\n    public string? Address { get; set; }\r\n}<\/pre>\n<h3><a id=\"H3\"><\/a>Creating Our Context Class<\/h3>\n<p>The context class is an important part of our application that we use to communicate with our database. This class inherits the base EF Core <code>DbContext<\/code> class that contains details for configuring and accessing the database.<\/p>\n<p>Let&#8217;s define a Context class named <code>ApplicationContext<\/code>\u00a0 in our <code>Models<\/code> folder:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class ApplicationContext(DbContextOptions&lt;ApplicationContext&gt; options) : DbContext(options)\r\n{\r\n    public DbSet&lt;Student&gt; Students { get; set; }\r\n\r\n    protected override void OnModelCreating(ModelBuilder modelBuilder)\r\n    {\r\n        modelBuilder.Entity&lt;Student&gt;().HasData(\r\n            new Student\r\n            {\r\n                Id = 1,\r\n                FirstName = \"John\",\r\n                LastName = \"Doe\",\r\n                Address = \"123 Main St\",\r\n            },\r\n            new Student\r\n            {\r\n                Id = 2,\r\n                FirstName = \"Jane\",\r\n                LastName = \"Doe\",\r\n                Address = \"456 Oak St\",\r\n            }\r\n        );\r\n    }\r\n}<\/pre>\n<p>In this <code>ApplicationContext<\/code> class, we first establish a <code>DbSet&lt;Student&gt;<\/code> object named <code>Students<\/code> to represent our entity. The <code>DbSet&lt;T&gt;<\/code> class provides methods for executing CRUD operations on the corresponding database tables in our database. Then, we override the <code>OnModelCreating()<\/code> method, utilizing the <code>HasData()<\/code> method to add seed data to our <code>Students<\/code> table.<\/p>\n<p>With that, let\u2019s add our database connection string to the <code>appsettings.json<\/code> file:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\" data-enlighter-highlight=\"8-10\">{\r\n  \"Logging\": {\r\n    \"LogLevel\": {\r\n      \"Default\": \"Information\",\r\n      \"Microsoft.AspNetCore\": \"Warning\"\r\n    }\r\n  },\r\n  \"ConnectionStrings\": {\r\n    \"StudentsConnection\": \"server=127.0.0.1;database=CodeMazeStudents;user=root;password=yourpassword;\"\r\n  },\r\n  \"AllowedHosts\": \"*\"\r\n}<\/pre>\n<p>In our connection string, <strong>we specify <code>127.0.0.1<\/code> (localhost) as the server. Then, we set the database name as <code>CodeMazeStudents<\/code><\/strong>. If a database with that name exists on our server, we use it. Otherwise, MariaDB will create a new database for us. The password <code>yourpassword<\/code> corresponds to the one we noted during the MariaDB installation.<\/p>\n<p>Now, we will move to the <code>Program.cs<\/code> file and register our <code>ApplicationContext<\/code> class as a service:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">builder.Services.AddDbContext&lt;ApplicationContext&gt;(options =&gt;\r\n{\r\n    var connectionString = builder.Configuration.GetConnectionString(\"StudentsConnection\");\r\n    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));\r\n});<\/pre>\n<p>Here, we define the connection details for our <code>ApplicationContext<\/code>. First, we call the <code>GetConnectionString()<\/code> method, with the <code>\"StudentsConnection\"<\/code> argument, to retrieve the connection string from our <code>appsettings.json<\/code> file.<\/p>\n<p>Subsequently, we configure our context to connect to a MySQL-compatible database by invoking the <code>UseMySql()<\/code> method. Here, we pass in the returned connection string, and the server version is automatically detected using the <code>ServerVersion.AutoDetect()<\/code> method.<\/p>\n<h3><a id=\"H3\"><\/a>Adding Migration and Updating the Database<\/h3>\n<p>We use the <a href=\"https:\/\/code-maze.com\/migrations-and-seed-data-efcore\/\" target=\"_blank\" rel=\"noopener\">EF Core migrations<\/a> feature to create and incrementally update our database schema based on our application&#8217;s models. To work with the migrations API, let&#8217;s install the <code>Microsoft.EntityFrameworkCore.Tools<\/code> NuGet package:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet add package Microsoft.EntityFrameworkCore.Tools<\/code><\/p>\n<p>Let\u2019s now add our first migration:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet ef migrations add FirstMigration<\/code><\/p>\n<p>After that, let&#8217;s create our database and schema:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">dotnet ef database update<\/code><\/p>\n<p>With everything set, we can now view our database with HeidiSQL:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/InitialStudentsDatabase.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-104056 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/InitialStudentsDatabase.png\" alt=\"Initial students database created with MariaDB\" width=\"613\" height=\"100\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/InitialStudentsDatabase.png 613w, https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/InitialStudentsDatabase-300x49.png 300w\" sizes=\"auto, (max-width: 613px) 100vw, 613px\" \/><\/a><\/p>\n<p>Now that we have seen what our database looks like, let\u2019s move on to the data access of our application.<\/p>\n<h2><a id=\"H2\"><\/a>Integrating Our MariaDB Database With Our ASP.NET Core App<\/h2>\n<p>Now, let&#8217;s define our <a href=\"https:\/\/code-maze.com\/net-core-web-development-part4\/\" target=\"_blank\" rel=\"noopener\">repository pattern<\/a> logic for performing CRUD operations (Creating, Reading, Updating, and Deleting) on our <code>CodeMazeStudents<\/code> database. After that, we&#8217;ll proceed to define the logic for our Web API controller.<\/p>\n<h3><a id=\"H3\"><\/a>Creating the Repository Logic<\/h3>\n<p>To implement a simple repository pattern, first, let\u2019s create a <code>Contracts<\/code> folder in our <code>Models<\/code> folder. Then, in this folder, let\u2019s add an interface:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public interface IDataRepository\r\n{\r\n    Task&lt;IEnumerable&lt;Student&gt;&gt; GetAllAsync();\r\n    Task&lt;Student?&gt; GetAsync(int id);\r\n    Task AddAsync(Student entity);\r\n    Task UpdateAsync(Student entityToUpdate, Student entity);\r\n    Task DeleteAsync(Student entity);\r\n}<\/pre>\n<p>This interface defines various asynchronous CRUD methods for data operations in our application. We will create a concrete class that implements this interface and uses our <code>ApplicationContext<\/code> to perform CRUD operations on our database.<\/p>\n<p>For this, let\u2019s create a <code>DataRepository<\/code> folder in the <code>Models<\/code> directory. In this folder, let\u2019s define a <code>StudentRepository<\/code> class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class StudentRepository(ApplicationContext context) : IDataRepository\r\n{\r\n    readonly ApplicationContext _studentContext = context;\r\n\r\n    public async Task AddAsync(Student entity)\r\n    {\r\n        _studentContext.Students.Add(entity);\r\n        await _studentContext.SaveChangesAsync();\r\n    }\r\n\r\n    public async Task&lt;Student?&gt; GetAsync(int id) =&gt; await _studentContext.Students.FindAsync(id);\r\n\r\n    public async Task UpdateAsync(Student entityToUpdate, Student entity)\r\n    {\r\n        entityToUpdate.FirstName = entity.FirstName;\r\n        entityToUpdate.LastName = entity.LastName;\r\n        entityToUpdate.Address = entity.Address;\r\n\r\n        await _studentContext.SaveChangesAsync();\r\n    }\r\n\r\n    public async Task DeleteAsync(Student entity)\r\n    {\r\n        _studentContext.Remove(entity);\r\n        await _studentContext.SaveChangesAsync();\r\n    }\r\n\r\n    public async Task&lt;IEnumerable&lt;Student&gt;&gt; GetAllAsync()\r\n    {\r\n        return await _studentContext.Students.ToListAsync&lt;Student&gt;();\r\n    }\r\n}<\/pre>\n<p>Here, we add logic for creating, reading, updating, and deleting student data. Additionally, we implement a method to retrieve all students in our database.<\/p>\n<p>With that, let\u2019s open the <code>Program.cs<\/code> file and register this class and the <code>IDataRepository<\/code> interface as a service:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">builder.Services.AddScoped&lt;IDataRepository, StudentRepository&gt;();<\/code><\/p>\n<p>Nice! Next up, let\u2019s create our Web API controller and add action methods to it.<\/p>\n<h3><a id=\"H3\"><\/a>Adding Our Controller<\/h3>\n<p>Controllers enable us to process HTTP requests, validate our models, and send back responses to our users.\u00a0<\/p>\n<p>So, let&#8217;s add a <code>StudentsController<\/code> class to the <code>Controllers<\/code> folder in our project:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[Route(\"api\/students\")]\r\n[ApiController]\r\npublic class StudentsController(IDataRepository dataRepository) : ControllerBase\r\n{\r\n    private readonly IDataRepository _dataRepository = dataRepository;\r\n}<\/pre>\n<p>Next, let&#8217;s define a <code>GetAllStudents()<\/code> method in this controller:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet]\r\npublic async Task&lt;IActionResult&gt; GetAllStudents()\r\n{\r\n    var students = await _dataRepository.GetAllAsync();\r\n\r\n    return Ok(students);\r\n}<\/pre>\n<p>Here, we call our data repository&#8217;s <code>GetAllAsync()<\/code> method to retrieve all the students in our database.<\/p>\n<p>Now, let&#8217;s create a <code>GetStudent()<\/code> action method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpGet(\"{id}\", Name = \"GetStudent\")]\r\npublic async Task&lt;IActionResult&gt; GetStudent(int id)\r\n{\r\n    var student = await _dataRepository.GetAsync(id);\r\n    if (student is null)\r\n    {\r\n        return NotFound(\"Student not found.\");\r\n    }\r\n\r\n    return Ok(student);\r\n}<\/pre>\n<p>For this action method, we specify that it is an <code>HttpGet<\/code> method with an <code>\"{id}\"<\/code> template. We set the route name of this method to <code>\"GetStudent\"<\/code>.<\/p>\n<p>Then, we try to retrieve the student from the database by calling the <code>GetAsync()<\/code> method with the provided id. If the student is null, we return a <code>404 Not Found<\/code> error. Otherwise, we call the <code>Ok()<\/code> method that returns an <code>OkObjectResult<\/code> object and a <code>200 OK<\/code> status code.<\/p>\n<p>Next, let&#8217;s define a <code>PostStudent()<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpPost]\r\npublic async Task&lt;IActionResult&gt; PostStudent([FromBody] Student student)\r\n{\r\n    if (student is null)\r\n    {\r\n        return BadRequest(\"Student is null.\");\r\n    }\r\n    await _dataRepository.AddAsync(student);\r\n\r\n    return CreatedAtRoute(\"GetStudent\", new { student.Id }, null);\r\n}<\/pre>\n<p>If the student that we want to add to our MariaDB database is null, we return a <code>400 Bad Request<\/code> error. If the student is not null, we add the student to our database and return a <code>201 Created<\/code> status code.<\/p>\n<p>Let&#8217;s now create a <code>PutStudent()<\/code> method in our controller:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpPut(\"{id}\")]\r\npublic async Task&lt;IActionResult&gt; PutStudent(int id, [FromBody] Student student)\r\n{\r\n    if (student is null)\r\n    {\r\n        return BadRequest(\"Student is null.\");\r\n    }\r\n\r\n    var studentToUpdate = await _dataRepository.GetAsync(id);\r\n    if (studentToUpdate is null)\r\n    {\r\n        return NotFound(\"The Student record couldn't be found.\");\r\n    }\r\n    await _dataRepository.UpdateAsync(studentToUpdate, student);\r\n\r\n    return NoContent();\r\n}<\/pre>\n<p>Once again, if the incoming student is null, we return a <code>400 Bad Request<\/code> error. Otherwise, we retrieve the existing student from the database. If we do not find the specified student, we return a <code>404 Not Found<\/code> response.<\/p>\n<p>Then, if the existing student is not null, we invoke our data repository&#8217;s <code>UpdateAsync()<\/code> method, passing in the existing student and the new student data. At the end, we return a <code>204 No Content<\/code> response.<\/p>\n<p>Finally, let&#8217;s define a <code>DeleteStudent()<\/code> action method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">[HttpDelete(\"{id}\")]\r\npublic async Task&lt;IActionResult&gt; DeleteStudent(int id)\r\n{\r\n    var student = await _dataRepository.GetAsync(id);\r\n    if (student is null)\r\n    {\r\n        return NotFound(\"The Student record couldn't be found.\");\r\n    }\r\n    await _dataRepository.DeleteAsync(student);\r\n\r\n    return NoContent();\r\n}<\/pre>\n<p>In this method, we first retrieve the student from our database. If the student is null, we return a <code>404 Not Found<\/code> response. Otherwise, we delete the student from our database and return a <code>204 No Content<\/code> response.<\/p>\n<p>Great! Our controller is now ready, and we can proceed to test our Web API and its interaction with our MariaDB database.<\/p>\n<h2><a id=\"H2\"><\/a>Testing the Web API With Postman<\/h2>\n<p>Now, let&#8217;s test our <code>StudentsController<\/code> endpoints with <a href=\"https:\/\/www.postman.com\/\" target=\"_blank\" rel=\"nofollow noopener\">Postman<\/a>.<\/p>\n<p>First, let&#8217;s visit our <code>GET<\/code> <code>https:\/\/localhost:7091\/api\/students<\/code> endpoint\u00a0and check the result:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">[\r\n    {\r\n        \"id\": 1,\r\n        \"firstName\": \"John\",\r\n        \"lastName\": \"Doe\",\r\n        \"address\": \"123 Main St\"\r\n    },\r\n    {\r\n        \"id\": 2,\r\n        \"firstName\": \"Jane\",\r\n        \"lastName\": \"Doe\",\r\n        \"address\": \"456 Oak St\"\r\n    }\r\n]<\/pre>\n<p>Next, let&#8217;s see what our <code>GET<\/code> <code>https:\/\/localhost:7091\/api\/students\/1<\/code> endpoint returns:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n    \"id\": 1,\r\n    \"firstName\": \"John\",\r\n    \"lastName\": \"Doe\",\r\n    \"address\": \"123 Main St\"\r\n}<\/pre>\n<p>With that, let&#8217;s look at the result of visiting our <code>POST<\/code> endpoint:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/PostStudentEndpoint-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-104057 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/PostStudentEndpoint-1.png\" alt=\"Post a student to our MariaDB database with ASP.NET Core Request\" width=\"672\" height=\"454\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/PostStudentEndpoint-1.png 672w, https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/PostStudentEndpoint-1-300x203.png 300w\" sizes=\"auto, (max-width: 672px) 100vw, 672px\" \/><\/a><\/p>\n<p>Now, let&#8217;s update our first student&#8217;s record:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/UpdateFirstStudent-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-104054 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/UpdateFirstStudent-1.png\" alt=\"Updating the first student record in the MariaDB database with ASP.NET Core Request\" width=\"666\" height=\"442\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/UpdateFirstStudent-1.png 666w, https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/UpdateFirstStudent-1-300x199.png 300w\" sizes=\"auto, (max-width: 666px) 100vw, 666px\" \/><\/a><\/p>\n<p>Finally, let&#8217;s delete a student from our database:<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/DeleteSeconndStudentEndpoint.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-104055 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/DeleteSeconndStudentEndpoint.png\" alt=\"Deleting the second student\" width=\"669\" height=\"171\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/DeleteSeconndStudentEndpoint.png 669w, https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/DeleteSeconndStudentEndpoint-300x77.png 300w\" sizes=\"auto, (max-width: 669px) 100vw, 669px\" \/><\/a><\/p>\n<p>That&#8217;s it. As we can see, all our endpoints are working perfectly.<\/p>\n<h2><a id=\"H2\"><\/a>Conclusion<\/h2>\n<p>In this article, we learned how to work with a MariaDB database in an ASP.NET Core Web API.<\/p>\n<p>Using EF Core&#8217;s code-first approach, we began our database design by defining our database model and ApplicationContext. Then, we created and applied our migrations. We also implemented all the CRUD operations.<\/p>\n<p>At the end, we used Postman to examine how our Web API interacts with our MariaDB database.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will discuss how to use a MariaDB database with an ASP.NET Core Web API. First, we will discuss what MariaDB is and how we include it in our application. Then, we will use the Entity Framework Core library to create a mapping between our Web API models and our MariaDB database. [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":62187,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[2079],"tags":[898,926,1811,2049],"class_list":["post-104053","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-api","tag-net-core-web-api","tag-asp-net","tag-c","tag-mariadb","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Using MariaDB With ASP.NET Core Web API - Code Maze<\/title>\n<meta name=\"description\" content=\"In this article, we discuss how to use a MariaDB database with an ASP.NET Core Web API and provide implementation for all the CRUD actions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Using MariaDB With ASP.NET Core Web API - Code Maze\" \/>\n<meta property=\"og:description\" content=\"In this article, we discuss how to use a MariaDB database with an ASP.NET Core Web API and provide implementation for all the CRUD actions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2024-01-23T11:18:03+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-01-31T14:52:31+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Januarius Njoku\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/cjaynjoku\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Januarius Njoku\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\"},\"author\":{\"name\":\"Januarius Njoku\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/c9d04eed48c29b9b10e3a0ec0fa77a18\"},\"headline\":\"Using MariaDB With ASP.NET Core Web API\",\"datePublished\":\"2024-01-23T11:18:03+00:00\",\"dateModified\":\"2024-01-31T14:52:31+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\"},\"wordCount\":1468,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"keywords\":[\".NET Core Web API\",\"ASP.NET\",\"C#\",\"MariaDb\"],\"articleSection\":[\"Web API\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\",\"url\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\",\"name\":\"Using MariaDB With ASP.NET Core Web API - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"datePublished\":\"2024-01-23T11:18:03+00:00\",\"dateModified\":\"2024-01-31T14:52:31+00:00\",\"description\":\"In this article, we discuss how to use a MariaDB database with an ASP.NET Core Web API and provide implementation for all the CRUD actions.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png\",\"width\":1100,\"height\":620,\"caption\":\"ASP.NET Core\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Using MariaDB With ASP.NET Core Web API\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/c9d04eed48c29b9b10e3a0ec0fa77a18\",\"name\":\"Januarius Njoku\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/Januarius-Njoku-150x150.jpeg\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/Januarius-Njoku-150x150.jpeg\",\"caption\":\"Januarius Njoku\"},\"description\":\"Januarius Njoku is a mechanical engineer who is passionate about using technology to improve the design and performance of mechanical systems. With experience in programming with C# and Python, he is also well-versed in DevOps technologies such as Ansible, Docker, and Puppet. Moreover, having a knack for writing, he has authored several technical articles on C# and .NET technologies. He is always on the lookout for new challenges and opportunities to learn and grow in the field of engineering and technology.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/in\/januariusnjoku\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/cjaynjoku\"],\"url\":\"https:\/\/code-maze.com\/author\/njokujennaro\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Using MariaDB With ASP.NET Core Web API - Code Maze","description":"In this article, we discuss how to use a MariaDB database with an ASP.NET Core Web API and provide implementation for all the CRUD actions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/","og_locale":"en_US","og_type":"article","og_title":"Using MariaDB With ASP.NET Core Web API - Code Maze","og_description":"In this article, we discuss how to use a MariaDB database with an ASP.NET Core Web API and provide implementation for all the CRUD actions.","og_url":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/","og_site_name":"Code Maze","article_published_time":"2024-01-23T11:18:03+00:00","article_modified_time":"2024-01-31T14:52:31+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","type":"image\/png"}],"author":"Januarius Njoku","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/cjaynjoku","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Januarius Njoku","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/"},"author":{"name":"Januarius Njoku","@id":"https:\/\/code-maze.com\/#\/schema\/person\/c9d04eed48c29b9b10e3a0ec0fa77a18"},"headline":"Using MariaDB With ASP.NET Core Web API","datePublished":"2024-01-23T11:18:03+00:00","dateModified":"2024-01-31T14:52:31+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/"},"wordCount":1468,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","keywords":[".NET Core Web API","ASP.NET","C#","MariaDb"],"articleSection":["Web API"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/","url":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/","name":"Using MariaDB With ASP.NET Core Web API - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","datePublished":"2024-01-23T11:18:03+00:00","dateModified":"2024-01-31T14:52:31+00:00","description":"In this article, we discuss how to use a MariaDB database with an ASP.NET Core Web API and provide implementation for all the CRUD actions.","breadcrumb":{"@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-aspnetcore.png","width":1100,"height":620,"caption":"ASP.NET Core"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/aspnetcore-using-mariadb-with-web-api\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Using MariaDB With ASP.NET Core Web API"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/c9d04eed48c29b9b10e3a0ec0fa77a18","name":"Januarius Njoku","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/Januarius-Njoku-150x150.jpeg","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2024\/01\/Januarius-Njoku-150x150.jpeg","caption":"Januarius Njoku"},"description":"Januarius Njoku is a mechanical engineer who is passionate about using technology to improve the design and performance of mechanical systems. With experience in programming with C# and Python, he is also well-versed in DevOps technologies such as Ansible, Docker, and Puppet. Moreover, having a knack for writing, he has authored several technical articles on C# and .NET technologies. He is always on the lookout for new challenges and opportunities to learn and grow in the field of engineering and technology.","sameAs":["https:\/\/www.linkedin.com\/in\/januariusnjoku\/","https:\/\/x.com\/https:\/\/twitter.com\/cjaynjoku"],"url":"https:\/\/code-maze.com\/author\/njokujennaro\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/104053","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=104053"}],"version-history":[{"count":4,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/104053\/revisions"}],"predecessor-version":[{"id":104063,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/104053\/revisions\/104063"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62187"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=104053"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=104053"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=104053"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}