IlikedCPlusPlus
IlikedCPlusPlus

Reputation: 57

ASP.NET.Core Web API can't connect to MariaDB database

I'm currently developing a ASP.NET Core Web-API which should work on a MariaDB 10.4 database. So far, whenever I start the IIS Server via Visual Studio 2019, no errors or warnings are thrown. The connection to said database is realized by using the EF core framework in combination with the Pomelo.Mysl library. The relevant files look as follows:

Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using racoon.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Pomelo.EntityFrameworkCore.MySql;

namespace racoon
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddDbContext<CollabradorContext>(options => options.UseMySql("Server=localhost;Database=db;User=usr;Password=foo;"));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
}

SampleContext.cs:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using racoon.Models;
using System.Net.Mime;

namespace racoon.Data
   {
public class SampleContext : DbContext
{
    public SampleContext(DbContextOptions<SampleContext> options) : base(options) {}

    public DbSet<Course> Courses { get;set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Course>().ToTable("Course");
    }
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace racoon.Models
    {
    public class Course
    {
        public long Id;
        public string Name;
        public string Description;
        public int Rating;
    }
}

DbInitalizer.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using racoon.Models;
using System.Threading.Tasks;

namespace racoon.Data
{
    public static class DbInitalizer
{
    public static void Initalize(CollabradorContext context)
    {
        System.Console.WriteLine("Initalize!");
        context.Database.EnsureCreated();

        if (context.Students.Any())
        {
            return;
        }

        var courses = new Course[]
        {
            new Course{Id=0,Name="Python",Description="Learn the fundamentals of Python",Rating=0},
            new Course{Id=1,Name="ML",Description="Learn everything about Machine Learning",Rating=0}
        };
        foreach (Course c in courses)
        {
            context.Courses.Add(c);
        }
        context.SaveChanges();
    }
}
}

Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using racoon.Data;

namespace racoon
{
    public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        host.Run();
    }

    private static void CreateDbIfNotExists(IHost host)
    {
        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<SampleContext>();
                context.Database.EnsureCreated();
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred creating the DB.");
            }
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}
}

Upvotes: 0

Views: 6705

Answers (1)

Sathish Guru V
Sathish Guru V

Reputation: 1499

Use options in the UseMySql to mention that you are connecting to a MariaDB instead of the default Mysql DB.

services.AddDbContext<CollabradorContext>(options => options      
                .UseMySql("Server=localhost;Database=db;User=usr;Password=foo;",      
                    mysqlOptions =>      
                        mysqlOptions.ServerVersion(new ServerVersion(new Version(10, 4, 6), ServerType.MariaDb))));

Upvotes: 1

Related Questions