Image
This article will summarize the development of Add-Ins for Outlook.  Use the basic template using Yeoman and Yeoman Generator. Development environment OS: Windows 11 .Net version: 8.0 Development tool: Visual Studio Code Node.js version: 18.20.4 Yeoman version: 5.0.0 Development language: React, Typescript

.Net Web API development based on MariaDb

 This article will cover how to implement Restful Web Api based on .Net 8.0 and how to import and save MariaDb data as Web Api.

Development environment

  • OS : Windows 11
  • .Net Version : 8.0
  • Development Tool : Visual Studio Code
  • MariaDb 11.5
  • EntiryFramework


1. Create Project

Open Powershell, go to the folder where you want to create the project, and run the dotnet new command as shown below.

   \>dotnet new webapi --use-controllers -o TodoApi

  • --use-controllers | -controllers : Controller-based Web API creation
  • -o : Target Output
Create a project using the dotnet new command in Powershell

2. Open project and add package

Open the project in Visual Studio Code and install Microsoft EntityFramework and MySql EntityFramework Package. When you click Ctrl+`, a terminal window opens at the bottom of Visual Studio Code. The command is as follows.

   \> dotnet add package Microsoft.EntityFrameworkCore
   \> dotnet add package MySql.EntityFrameworkCore

Search for SQLTools in Visual Studio Code Extensions and install SQLTools MySQL/MariaDB/TiDB Extension.
You can connect to MariaDb with this extension.
Visual Studio Code Extension screen


3. Model/DbContext creation and service registration

First, the MariaDb table schema is as follows.

db: tutorial, table : todo
columntype비고
idvarchar(50)PK
datedatePK
titletext 
is_completetinyint(1) 


  • Create Model Class
[Table("todo"Schema = "tutorial")]
    public class TodoItem
    {
        [Column("id")]
        public string Id { getset; } = "";

        [Column("date")]
        public DateTime Date { getset; }

        [Column("title")]
        public string Title { getset; } = "";

        [Column("is_complete")]
        public bool IsComplete { getset; }
    }
    • Create DbContext
public class TutorialDbContext : DbContext
    {
        public TutorialDbContext(DbContextOptions options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TodoItem>().HasKey(x => new { x.Idx.Date });
        }

        public DbSet<TodoItemTodoItems { getset; }
    }
    • Register ConnectionString in appsettings.Development.json
"ConnectionStrings": {
    "Tutorial""server=localhost; port=3306; database=tutorial; user=root; password=********"
  }
    • Register DbContext in Program.cs
builder.Services.AddDbContext<TutorialDbContext>(
    option => option.UseMySQL(
        builder.Configuration.GetConnectionString("Tutorial")!));

4. Create Service class and register it in Program.cs

Create a service class that uses TutorialDbContext.
public class TodoService
    {
        private readonly TutorialDbContext _dbContext;
        public TodoService(TutorialDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<List<TodoItem>> GetTodoItems()
        {
            var list = await _dbContext.TodoItems.ToListAsync();
            return list;
        }

        public async Task<TodoItem?GetTodoItem(string idDateTime date)
        {
            var sql = "SELECT * FROM todo WHERE id = ?id AND date = ?date";
            var parameters = new MySqlParameter[2];
            parameters[0= new MySqlParameter() { Value = idParameterName = "id" };
            parameters[1= new MySqlParameter() { Value = dateParameterName = "date" };

            var list = await _dbContext.TodoItems.FromSqlRaw(sqlparameters).ToListAsync();
            return list.FirstOrDefault();
        }

        public async Task PostTodoItem(TodoItem item)
        {
            var savedItem = await GetTodoItem(item.Iditem.Date);
            if (savedItem == null)
            {
                _dbContext.Add(item);
            }
            else
            {
                _dbContext.Entry(savedItem).CurrentValues.SetValues(item);
            }
            await _dbContext.SaveChangesAsync();
        }
    }
 
   Register the created TodoService as a service in Program.cs.

builder.Services.AddScoped<TodoService>();
 
 

5. Create Controller and Write Http Method

Create a TodoApiController class that inherits the ControllerBase class.

[ApiController]
    [Route("api/[controller]")]
    public class TodoApiController : ControllerBase
    {
        private readonly TodoService _todoService;
        public TodoApiController(TodoService todoService)
        {
            _todoService = todoService;
        }

        [HttpGet]
        [Route("todoitems")]
        public async Task<ActionResult<List<TodoItem>>> GetTodoItems()
        {
            var list = await _todoService.GetTodoItems();
            return Ok(list);
        }

        [HttpGet]
        [Route("todoitem/{id}/{date}")]
        public async Task<ActionResult<TodoItem>> GetTodoItem(string idDateTime date)
        {
            var item = await _todoService.GetTodoItem(iddate);
            return Ok(item);
        }

        [HttpPost]
        public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem item)
        {
            await _todoService.PostTodoItem(item);

            return CreatedAtAction(nameof(GetTodoItem), new { id = item.Iddate = item.Date }, item);
        }
    }


6. Build and test

Run the command below in Powershell.

   \>dotnet watch run

Execute and test each method on the Swagger screen.
swagger screen👆


Reference 

Comments

Popular posts from this blog

Setting up Windows Powershell with Oh-My-Posh

[NETSDK1136] the target platform must be set to windows