ASP.NET Core 下使用 EFCore 和 .NET Framework 下使用有點區(qū)別。
參考官方文檔:https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core.html
1.創(chuàng)建 ASP.NET Core Web應(yīng)用 項目
創(chuàng)建新的項目的 Program.cs 文件中使用了頂級語句,與NET5 有所區(qū)別。
.NET 6 的 創(chuàng)建的項目使用了C# 頂級語句
https://learn.microsoft.com/zh-cn/dotnet/csharp/whats-new/tutorials/top-level-statements
2.引入相關(guān)nuget包
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="MySql.Data" Version="8.0.31" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="6.0.7" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.1.4" />
</ItemGroup>
3.創(chuàng)建AppDbContext類
注意: this.Database.EnsureCreated();初始化數(shù)據(jù)庫,如果不存在數(shù)據(jù)庫會創(chuàng)建。
using Microsoft.EntityFrameworkCore;
public class AppDbContext: DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {
// 初始化數(shù)據(jù)庫,如果不存在數(shù)據(jù)庫會創(chuàng)建
this.Database.EnsureCreated();
}
public DbSet<Models.User> User{ get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// optionsBuilder.UseMySQL("server=localhost;database=library;user=user;password=password");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(e => e.id);
});
}
}
4.添加連接字符串配置appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MySQLConnection": "server=127.0.0.1;port=3306;uid=root;database=db1"
}
}
在var builder = WebApplication.CreateBuilder(args);代碼下添加文章來源:http://www.zghlxwxcb.cn/news/detail-469436.html
builder.Services.AddDbContext<AppDbContext>(opt =>
{
opt.UseMySQL(builder.Configuration.GetConnectionString("MySQLConnection"));
});
最終可以在Controller相關(guān)代碼中注入 AppDbContext 來操作數(shù)據(jù)庫。文章來源地址http://www.zghlxwxcb.cn/news/detail-469436.html
到了這里,關(guān)于ASP.NET Core NET6 EFCore MySQL的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!