net 8.0 + mysql 数据库的应用与实现

本文介绍了如何在.NETCore项目中使用Nutget包引入EntityFramework,配置数据库连接,创建SqlContent类,定义YFTB_LoginUser实体,并在LoginController中操作数据库。
摘要由CSDN通过智能技术生成

首先引入nutget包

第二步根目录创建一个文件夹名字自取,再建一个SqlContent类

using Microsoft.EntityFrameworkCore;
using System.Data.Entity;
using DbContext = Microsoft.EntityFrameworkCore.DbContext;

namespace YuanFuTouBao2022Core.Dao
{
	public class SqlContext : DbContext
	{
		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			base.OnConfiguring(optionsBuilder);
			string connectStr = "server=.;port=3306;database=aaa;uid=aaa;pwd=123;CharSet=utf8";
			//注意了,下面的那么Version是mysql的版本号,8.0.3是我的版本号,你可以通过在cmd中输入
			//mysql --help查看自己的版本号
			optionsBuilder.UseMySql
				(connectStr, new MySqlServerVersion(new Version(8, 0, 29)));
		}

		protected override void OnModelCreating(ModelBuilder modelBuilder)
		{
			base.OnModelCreating(modelBuilder);
			modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
		}

		public Microsoft.EntityFrameworkCore.DbSet<YFTB_LoginUser> YFTB_LoginUser { get; set; }
	}
}

把实体类YFTB_LoginUser加上

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace YuanFuTouBao2022Core.Dao
{
	[Table("YFTB_LoginUser")]
	public class YFTB_LoginUser
	{
		[Key]
		[Column("id")]
		public int ID { get; set; }
		[Column("name")]
		public string name { get; set; }
		[Column("pwd")]
		public string pwd { get; set; }

	}
}

ok 搞定

最后在controller中 使用即可

namespace XinHua2021.Controllers
{
	
	public class LoginController : Controller
    {
       
		SqlContext sqlContext = new SqlContext();
		
		public IActionResult Index()
		{
			var a = sqlContext.YFTB_LoginUser.ToList();


			return View();
		}
	}
}

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值