本文介绍在EF Core中基于现有数据库的MySQL使用。
开发平台最低要求(Windows):
- Connector/NET 8.0.22
- MySQL Server 5.6
- Entity Framework Core
- .NET Standard 2.1 (.NET Core SDK 3.1 and Visual Studio 2019 version 16.5)
1.安装 NuGet 包
Install-Package MySql.EntityFrameworkCore -Version 5.0.5
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0.9
2.实体模型搭建
1.从现有数据库通过控制台命令生成实体框架模型:
Scaffold-DbContext “server=127.0.0.1;database=zhongtiesync;uid=root;password=123456;” MySql.EntityFrameworkCore -OutputDir sakila -f
2.指定表生成实体模型:
Scaffold-DbContext “server=127.0.0.1;database=zhongtiesync;uid=root;password=123456;” MySql.EntityFrameworkCore -OutputDir Sakila -Tables actor,film,language -f
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace Core.Entitys
{
public partial class zhongtiesyncContext : DbContext
{
public zhongtiesyncContext()
{
// Creates the database if not exists
this.Database.EnsureCreated();
}
public zhongtiesyncContext(DbContextOptions<zhongtiesyncContext> options)
: base(options)
{
}
public virtual DbSet<Department> Departments {
get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder