.net core connect local mysql
choose mysql
local with mamp or docker
---
install
nuget
Pomelo.EntityFrameworkCore.MySql
---
in appsettings.json:
"ConnectionStrings": {
"DefaultConnection": "server=localhost;port=3306;database=dotnetmysqltest;uid=username;password=password",
}
setup entities
recipe.class
using System;
using System.Collections.Generic;
namespace testlocalmysql.Entities
{
public class Recipe
{
public int RecipeId { get; set; }
public string Name { get; set; }
// public TimeSpan TimeToCook { get; set; } // gave error time(6) ???
// works as double
public double TimeToCook { get; set; }
public bool IsDeleted { get; set; }
public string Method { get; set; }
public ICollection<Ingredient> Ingredients { get; set; }
}
}
ingredient.class
using System;
namespace testlocalmysql.Entities
{
public class Ingredient
{
public int IngredientId { get; set; }
public int RecipeId { get; set; }
public string Name { get; set; }
public decimal Quantity { get; set; }
public string Unit { get; set; }
}
}
register dbcontext
using System;
using Microsoft.EntityFrameworkCore;
using testlocalmysql.Entities;
namespace testlocalmysql.Db
{
public class AppDbContext: DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Recipe> Recipes { get; set; }
}
}
add to startup.cs
services.AddDbContext<AppDbContext>(options =>
options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
use ef
test if works
dotnet ef --help
apply first migration
dotnet ef migrations add InitialSchema
migration folder is created with 3 new files
finish it with
dotnet ef database update