C#-EF Core使用MySQL数据库

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: Entity Framework Core (EF Core)是微软推荐的基于.NET Core 的应用程序数据访问技术。开源,轻量级,可扩展并且支持跨平台开发。EF Core是一种对象关系映射器(ORM),通过应用程序实体对象和关系数据库中的数据的映射,使得开发人员能够以面向对象的方式处理数据。

简介

Entity Framework Core (EF Core)是微软推荐的基于.NET Core 的应用程序数据访问技术。开源,轻量级,可扩展并且支持跨平台开发。EF Core是一种对象关系映射器(ORM),通过应用程序实体对象和关系数据库中的数据的映射,使得开发人员能够以面向对象的方式处理数据。

使用

在项目里头安装EF Core和MySQL相关的NuGet包:Microsoft.EntityFrameworkCorePomelo.EntityFrameworkCore.MySql ,如果你使用的是其他数据库,那么就换成其他的数据库相关的包即可。

这里创建的是一个web项目,桌面项目其实大同小异,创建一个类继承DbContext,DbContext 是 EF 中非常重要的一个组件,它拥有数据库的会话连接,数据查询,修改保存数据,缓存,事务管理等等作用。

比如我这里创建的是这样的:

usingAcg.Models;
usingMicrosoft.EntityFrameworkCore;
namespaceAcg.DataBase{
publicclassAcgbiuDbContext : DbContext    {
publicDbSet<TopicModel>Acgbiu_Topic { get; set; }
publicDbSet<TopicRelationshipsModel>Acgbiu_Topic_Relationships { get; set; }
publicDbSet<TermModel>Acgbiu_Terms { get; set; }
publicDbSet<FocusModel>Acgbiu_Focus { get; set; }
publicAcgbiuDbContext(DbContextOptions<AcgbiuDbContext>options) : base(options)
        {
this.Database.Migrate();
        }
protectedoverridevoidOnModelCreating(ModelBuildermodelBuilder)
        {
modelBuilder.Entity<TopicModel>();
modelBuilder.Entity<TopicRelationshipsModel>();
modelBuilder.Entity<FocusModel>();
        }
    }
}

创建实体类,对应数据库中的表结构,比如我这里的TopicModel

usingSystem.ComponentModel.DataAnnotations;
usingSystem.ComponentModel.DataAnnotations.Schema;
namespaceAcg.Models{
    [Table("acgbiu_topic")]
publicclassTopicModel    {
        [Key]
publicinttopic_id { get; set; }
publicstringname { get; set; }
publicstringdescription { get; set; }
publicstringicon { get; set; }
publicstringremark { get; set; }
    }
}

使用依赖注入的方式使用刚才创建的AcgbiuDbContext ,在Startup.cs中注册AcgbiuDbContext。

publicvoidConfigureServices(IServiceCollectionservices)
        {
services.AddControllersWithViews();
stringconnectStr=$"server = 服务器地址; port=端口号;database = 使用的数据库; uid = 数据库连接用户名; password = 密码";
services.AddDbContext<AcgbiuDbContext>(oprions=>oprions.UseMySql(connectStr, newMySqlServerVersion(newVersion(10,5,6))));
        }

以一个控制器类的代码为例,看下数据的增删改查。

构造函数注入的方式,获取我们刚才注册的AcgbiuDbContext,然后就可以使用了。

//获取表的所有数据AcgbiuDbContext.Acgbiu_Topic.ToList();
//添加数据AcgbiuDbContext.Acgbiu_Topic.Add(topicModel);
//更新数据AcgbiuDbContext.Acgbiu_Topic.Update(topicModel);
//删除数据AcgbiuDbContext.Acgbiu_Topic.Remove(topic);
//异步的方式将前面的增删改,保存到数据库中awaitAcgbiuDbContext.SaveChangesAsync();
usingAcg.DataBase;
usingAcg.Models;
usingMicrosoft.AspNetCore.Mvc;
usingMicrosoft.Extensions.Configuration;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Threading.Tasks;
namespaceAcg.Controllers{
    [Route("Api/[controller]/[action]/{id?}")]
publicclassApiTopicController: ControllerBase    {
privatereadonlyIConfigurationConfiguration;
privatereadonlyAcgbiuDbContextAcgbiuDbContext;
publicApiTopicController(IConfigurationconfiguration, AcgbiuDbContextacgbiuDbContext) 
        {
Configuration=configuration;
AcgbiuDbContext=acgbiuDbContext;
        }
        [HttpGet]
publicasyncTask<IActionResult>Topics(intid)
        {
List<TopicModel>topicModels=newList<TopicModel>();
topicModels=AcgbiuDbContext.Acgbiu_Topic.ToList();
if (id!=0) 
            {
TopicModeltopicModel=topicModels.Find(x=>x.topic_id==id);
returnnewJsonResult(topicModel);
            }
returnnewJsonResult(topicModels);
        }
        [HttpPost]
publicasyncTask<IActionResult>Topics([FromBody] TopicModeltopicModel)
        {
boolres=true;
AcgbiuDbContext.Acgbiu_Topic.Add(topicModel);
intnum=awaitAcgbiuDbContext.SaveChangesAsync();
if (num<=0)
            {
res=false;
            }
returnnewJsonResult(num);
        }
        [HttpPut]
publicasyncTask<IActionResult>Topics(intid,[FromBody]TopicModeltopicModel)
        {
boolres=true;
if (id!=topicModel.topic_id) 
            {
returnBadRequest();
            }
AcgbiuDbContext.Acgbiu_Topic.Update(topicModel);
intnum=awaitAcgbiuDbContext.SaveChangesAsync();
returnnewJsonResult(num);
        }
        [HttpDelete]
publicasyncTask<IActionResult>Topics(longid)
        {
vartopic=awaitAcgbiuDbContext.Acgbiu_Topic.FindAsync(id);
if (topic==null)
            {
returnNotFound();
            }
AcgbiuDbContext.Acgbiu_Topic.Remove(topic);
awaitAcgbiuDbContext.SaveChangesAsync();
returnNoContent();
        }
        [HttpGet]
publicasyncTask<IActionResult>TopicTerms(intid)
        {
if (id>0)
            {
varterms=AcgbiuDbContext.Acgbiu_Topic_Relationships.Join(AcgbiuDbContext.Acgbiu_Terms, x=>x.term_id, y=>y.term_id, (x, y) =>new                {
x.id,
x.topic_id,
x.term_id,
y.name,
y.slug                }).Where(p=>p.topic_id==id).ToList();
returnnewJsonResult(terms);
            }
else            {
varterms=AcgbiuDbContext.Acgbiu_Topic_Relationships.Join(AcgbiuDbContext.Acgbiu_Terms, x=>x.term_id, y=>y.term_id, (x, y) =>new                {
x.id,
x.topic_id,
x.term_id,
y.name,
y.slug                }).ToList();
returnnewJsonResult(terms);
            }
        }
        [HttpPost]
publicasyncTask<IActionResult>TopicTerms([FromBody] TopicRelationshipsModeltopicRelationshipsModel)
        {
try            {
if (topicRelationshipsModel==null||topicRelationshipsModel.topic_id==0||topicRelationshipsModel.term_id==0)
                {
returnBadRequest();
                }
boolisExist=AcgbiuDbContext.Acgbiu_Topic_Relationships.Any(x=>x.topic_id==topicRelationshipsModel.topic_id&&x.term_id==topicRelationshipsModel.term_id);
if (!isExist) 
                {
awaitAcgbiuDbContext.Acgbiu_Topic_Relationships.AddAsync(topicRelationshipsModel);
awaitAcgbiuDbContext.SaveChangesAsync();
                }
else                {
returnBadRequest();
                }
            }catch(Exceptionex)
            {
returnBadRequest();
            }
returnNoContent();
        }
    }
}

参考

Entity Framework Core 概述 – EF Core | Microsoft Learn

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
3
分享
相关文章
C#使用SqlSugar操作MySQL数据库实现简单的增删改查
C#使用SqlSugar操作MySQL数据库实现简单的增删改查
462 2
ASP.NET Web Api 使用 EF 6,DateTime 字段如何取数据库服务器当前时间
ASP.NET Web Api 使用 EF 6,DateTime 字段如何取数据库服务器当前时间
123 0
【Entity Framework】聊一聊EF如何使用数据库函数
【Entity Framework】聊一聊EF如何使用数据库函数
218 0
【Entity Framework】EF中的增删改查
【Entity Framework】EF中的增删改查
272 0
C# .NET面试系列三:集合、异常、泛型、LINQ、委托、EF!
<h2>集合、异常、泛型、LINQ、委托、EF! #### 1. IList 接口与 List 的区别是什么? IList 接口和 List 类是C#中集合的两个相关但不同的概念。下面是它们的主要区别: <b>IList 接口</b> IList 接口是C#中定义的一个泛型接口,位于 System.Collections 命名空间。它派生自 ICollection 接口,定义了一个可以通过索引访问的有序集合。 ```c# IList 接口包含一系列索引化的属性和方法,允许按索引访问、插入、移除元素等。 由于是接口,它只定义了成员的契约,而不提供具体的实现。类似于 IEnumera
552 2
【Unity 3D】C#从mysql数据库中读取、封装SQL语句(附源码)
【Unity 3D】C#从mysql数据库中读取、封装SQL语句(附源码)
440 0
数据库运维:mysql 数据库迁移方法-mysqldump
本文介绍了MySQL数据库迁移的方法与技巧,重点探讨了数据量大小对迁移方式的影响。对于10GB以下的小型数据库,推荐使用mysqldump进行逻辑导出和source导入;10GB以上可考虑mydumper与myloader工具;100GB以上则建议物理迁移。文中还提供了统计数据库及表空间大小的SQL语句,并讲解了如何使用mysqldump导出存储过程、函数和数据结构。通过结合实际应用场景选择合适的工具与方法,可实现高效的数据迁移。
101 1

热门文章

最新文章

推荐镜像

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问