.NET6 + EF Core + MySQL 创建实体和数据库、EFCore 数据迁移、属性导航
一、创建 asp.net core web(MVC)项目
二、导包
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntifyFrameworkCore.Tools
- Pomelo.EntityFrameworkCore.MySql
三、创建实例
这里创建了两个实例
namespace demo.Models
{
public class Supplier
{
[key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]//自增
public long SupplierId { get; set; }
public string SupplierName { get; set; }
public string Abbreviation { get; set; }
public List<SupplierType> SupplierTypes { get; set; } = new List<SupplierType>();
public string province { get; set; }
public string City { get; set; }
public string Address { get; set; }
public string Note { get; set; }
public bool IsActive { get; set; }
}
}
namespace demo.Models
{
public class SupplierType
{
[Key]
public int TypeCode { get; set; }
public string TypeName { get; set; }
public Supplier Supplier { get; set; }
public long SupplierSupplierId{ get; set}
}
}
四、为实体类创建配置
namespace demo.Data
{
public class SupplierConfig : IEntityTypeConfiguration<Supplier>
{
public void Configure(EntityTypeBuilder<Supplier> builder)
{
builder.ToTable("T_Supplier");
builder.Property(a => a.SupplierId).IsRequired();//不能为空
builder.Property(a => a.SupplierName).IsRequired();
builder.Property(a => a.SupplierTypes).IsRequired();
}
}
namespace demo.Data
{
public class SupplierTypeConfig : IEntityTypeConfiguration<SupplierType>
{
public void Configure(EntityTypeBuilder<SupplierType> builder)
{
builder.ToTable("SupplierType");
builder.HasOne<Supplier>(c => c.Supplier).WithMany(a => a.SupplierTypes);//属性导航
}
}
}
五、创建数据上下文类
创建MyDbContext.cs 继承DbContext
MyDbContext namespace demo.Data
{
public class MyDbContext:DbContext
{
//添加实体类
public DbSet<Supplier> suppliers{ get; set; }
public DbSet<SupplierType> supplierTypes { get; set; }
//构造函数
public MyDbContext(DbContextOptions<MyDbContext> option) : base(option) { }
}
}
六、连接MySql配置
- 查询mysql版本
- 配置appsettings.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "DefaultConnection": "server=localhost;port=3306;uid=root;pwd=123456;database=demo1"// demo1创建的数据库名 } }
<!--配置sqlserver-->
"ConnectionStrings": {
"BlazorShopContext": "Server=localhost;Database=Demo;uid=sa;pwd=123456;TrustServerCertificate=true"
} - 配置Program.cs
public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); //配置这段代码 builder.Services.AddDbContext<MyDbContext>(options => { options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), new MySqlServerVersion(new Version(5, 7, 26))); });//5 7 26为数据库版本,DefaultConnection 对应json配置的名
//配置sqlserver
uilder.Services.AddDbContext<BlazorShopContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("BlazorShopContext")
));var app = builder.Build();//一定要在 var app = builder.Build();上面配置,否则不会构建 // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); } }
迁移
Add-Migration init
Update-Database