Asp.net core2.2利用Entity Framework Core连接Mysql数据库

it2023-03-21  83

1、Asp.net core环境是2.2的

2、利用NuGet下载安装MySql.Data.EntityFrameworkCore8.0.18版的库,其他版的连接时可能会报错。

3、创建数据库对象类,例如Product,放在Models文件夹下

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Lessoon2._1.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public decimal Weight { get; set; } } }

4、在MySql下创建Products数据库,该数据库名称与第5步的DbSet<Product> Products中的Products同名

5、创建Context类,创建context文件夹,并在改文件夹下创建ApplicationDbContext类

using Lessoon2._1.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Lessoon2._1.Context { public class ApplicationDbContext:DbContext { public ApplicationDbContext(DbContextOptions options):base(options) { } public DbSet<Product> products { get; set; } } }

6、在控制器下进行连接数据库,添加数据操作

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Lessoon2._1.Models; using Microsoft.EntityFrameworkCore; using Lessoon2._1.Context; namespace Lessoon2._1.Controllers { public class HomeController : Controller { public IActionResult Index() { Product product = new Product(); product.Name = "西瓜"; product.Price = 34; product.Weight = 98; string DefaultMySqlConnectionString = "server=localhost;userid=root;pwd=mj123;port=3306;database=test;SslMode=None"; DbContextOptionsBuilder builder = new DbContextOptionsBuilder(); builder.UseMySQL(DefaultMySqlConnectionString); using (ApplicationDbContext context = new ApplicationDbContext(builder.Options)) { context.products.Add(product); context.SaveChanges(); } return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }

 

最新回复(0)