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

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 });
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值