.NetCore中EFCore for MySql整理MySql.EntityFrameworkCore
一、MySql.EntityFrameworkCore
这个是官方给的一个EF操作MySql数据库的框架。
使用方法跟EF for SqlServer 一样。
二、安装命令
NuGet\Install-Package MySql.EntityFrameworkCore -Version 8.0.5
项目依赖
安装后的结果:
三、 EF Code First 模式连接数据库
1. 数据库上下文
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using Microsoft.EntityFrameworkCore; namespace Md5.Factory { public class MyContext : DbContext { /// <summary> /// 链接字符串 /// </summary> public static string SqlStr { get; set; } public virtual DbSet<dy_adstype> dy_adstype { get; set; } //启动配置 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseMySQL(SqlStr); } } } }
2.实体模型
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System { public class dy_adstype { [Key] public int taid { get; set; } public string Name { get; set; } public int adsw { get; set; } public int adsh { get; set; } } }
3.使用案例
string MySqlStr = "Server=xxx;port=3306;Database=xxx;uid=root;pwd=xxx"; MyContext.SqlStr = MySqlStr; MyContext _context = new MyContext(); int count = _context.dy_adstype.Count(); Console.WriteLine(count); foreach (var item in _context.dy_adstype.ToList()) { Console.WriteLine(item.Name); }
更多:
分类:
.Net Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?