首页 > 数据库 >C#-EF Core使用MySQL数据库

C#-EF Core使用MySQL数据库

时间:2023-03-02 23:06:33浏览次数:35  
标签:Core C# EF public Topic topic Acgbiu AcgbiuDbContext id

简介

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

使用

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

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

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

using Acg.Models;
using Microsoft.EntityFrameworkCore;

namespace Acg.DataBase
{
    public class AcgbiuDbContext : DbContext
    {
        public DbSet<TopicModel> Acgbiu_Topic { get; set; }
        public DbSet<TopicRelationshipsModel> Acgbiu_Topic_Relationships { get; set; }
        public DbSet<TermModel> Acgbiu_Terms { get; set; }
        public DbSet<FocusModel> Acgbiu_Focus { get; set; }
        public AcgbiuDbContext(DbContextOptions<AcgbiuDbContext> options) : base(options)
        {
            this.Database.Migrate();
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TopicModel>();
            modelBuilder.Entity<TopicRelationshipsModel>();
            modelBuilder.Entity<FocusModel>();
        }
    }
}

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

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

namespace Acg.Models
{
    [Table("acgbiu_topic")]
    public class TopicModel
    {
        [Key]
        public int topic_id { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
        public string remark { get; set; }
    }
}

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

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            string connectStr = $"server = 服务器地址; port=端口号;database = 使用的数据库; uid = 数据库连接用户名; password = 密码";
            services.AddDbContext<AcgbiuDbContext>(oprions => oprions.UseMySql(connectStr, new MySqlServerVersion(new Version(10,5,6))));
        }

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

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

//获取表的所有数据
AcgbiuDbContext.Acgbiu_Topic.ToList();

//添加数据
AcgbiuDbContext.Acgbiu_Topic.Add(topicModel);

//更新数据
AcgbiuDbContext.Acgbiu_Topic.Update(topicModel);

//删除数据
AcgbiuDbContext.Acgbiu_Topic.Remove(topic);

//异步的方式将前面的增删改,保存到数据库中
await AcgbiuDbContext.SaveChangesAsync();
using Acg.DataBase;
using Acg.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Acg.Controllers
{
    [Route("Api/[controller]/[action]/{id?}")]
    public class ApiTopicController: ControllerBase
    {
        private readonly IConfiguration Configuration;
        private readonly AcgbiuDbContext AcgbiuDbContext;
        public ApiTopicController(IConfiguration configuration, AcgbiuDbContext acgbiuDbContext) 
        {
            Configuration=configuration;
            AcgbiuDbContext = acgbiuDbContext;
        }
        [HttpGet]
        public async Task<IActionResult> Topics(int id)
        {
            List<TopicModel> topicModels = new List<TopicModel>();
            topicModels = AcgbiuDbContext.Acgbiu_Topic.ToList();
            if (id != 0) 
            {
                TopicModel topicModel = topicModels.Find(x=>x.topic_id==id);
                return new JsonResult(topicModel);
            }
            return new JsonResult(topicModels);
        }
        
        [HttpPost]
        public async Task<IActionResult> Topics([FromBody] TopicModel topicModel)
        {
            bool res = true;
            AcgbiuDbContext.Acgbiu_Topic.Add(topicModel);
            int num=await AcgbiuDbContext.SaveChangesAsync();
            if (num <= 0)
            {
                res = false;
            }
            return new JsonResult(num);
        }
        [HttpPut]
        public async Task<IActionResult> Topics(int id,[FromBody]TopicModel topicModel)
        {
            bool res = true;
            if (id != topicModel.topic_id) 
            {
                return BadRequest();
            }
            AcgbiuDbContext.Acgbiu_Topic.Update(topicModel);
            int num = await AcgbiuDbContext.SaveChangesAsync();
            return new JsonResult(num);
        }
        [HttpDelete]
        public async Task<IActionResult> Topics(long id)
        {
            var topic = await AcgbiuDbContext.Acgbiu_Topic.FindAsync(id);
            if (topic == null)
            {
                return NotFound();
            }
            AcgbiuDbContext.Acgbiu_Topic.Remove(topic);
            await AcgbiuDbContext.SaveChangesAsync();
            return NoContent();
        }

        [HttpGet]
        public async Task<IActionResult> TopicTerms(int id)
        {
            if (id > 0)
            {
                var terms = 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();
                return new JsonResult(terms);
            }
            else
            {
                var terms = 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();
                return new JsonResult(terms);
            }
        }

        [HttpPost]
        public async Task<IActionResult> TopicTerms([FromBody] TopicRelationshipsModel topicRelationshipsModel)
        {
            try
            {
                if (topicRelationshipsModel==null||topicRelationshipsModel.topic_id==0|| topicRelationshipsModel.term_id==0)
                {
                    return BadRequest();
                }
                bool isExist = AcgbiuDbContext.Acgbiu_Topic_Relationships.Any(x=>x.topic_id==topicRelationshipsModel.topic_id&&x.term_id==topicRelationshipsModel.term_id);
                if (!isExist) 
                {
                    await AcgbiuDbContext.Acgbiu_Topic_Relationships.AddAsync(topicRelationshipsModel);
                    await AcgbiuDbContext.SaveChangesAsync();
                }
                else
                {
                    return BadRequest();
                }
                
            }catch(Exception ex)
            {
                return BadRequest();
            }
            return NoContent();
        }
    }
}

标签:Core,C#,EF,public,Topic,topic,Acgbiu,AcgbiuDbContext,id
From: https://blog.51cto.com/u_14690667/6096789

相关文章

  • 10_Spring_CGLIB动态代理
     proxy动态代理面向接口1必须有接口和实现类 2增强接口中定义的方法3只能读取接口中方法的上注解cglib动态代理模式面向父类 packagecom.msb.testCglib;importo......
  • 10_Spring_CGLIB动态代理
     proxy动态代理面向接口1必须有接口和实现类 2增强接口中定义的方法3只能读取接口中方法的上注解cglib动态代理模式面向父类 packagecom.msb.testCglib;importo......
  • OpenCloudOS 如何以最小成本,高效定位内存泄露路径?
    导读|遭受内存泄露往往是令开发者头疼的问题,传统分析工具gdb、Valgrind在解决内存泄露问题上效率较低。本文特别邀请到了OpenCloudOS社区Contributor、腾讯后台开发工程......
  • Redmibook 14 EE 电脑 Hackintosh 黑苹果efi引导文件
    硬件型号驱动情况主板Redmibook14EE处理器IntelCorei5-10210Uandi7已驱动内存16GBLPDDR4X3200MHz已驱动硬盘金士顿512G已驱动显卡IntelUHDGraphics10thGen,NV......
  • msvcr100.dll丢失是什么意思-msvcr100.dll丢失解决方法
    丢失msvcr100.dll或者损坏会导致电脑很多软件跟游戏都无法正常打开运行。还有不少小伙伴不知道怎么修复,小编今天就把修复教程分享给大家;最简单的修复方法电脑开机打开任意一......
  • grafana-piechart-panel 安装
    grafana-piechart-panelPanelpluginnotfound:grafana-piechart-panel错误grafana安装grafana-piechart-panel插件是成功的1.安装grafana-clipluginsinstallgrafana-p......
  • C# 实现你自己的异步方法
    背景最近在重构自己曾经的代码,具体需求是在Unity等待如一个模型动画,一段ui动画如下:Await的目标await的目标是一个可等待对象,而拥有GetAwaiter方法并且该方法拥有合......
  • [转]Windows10下CLion配置说明
    Windows10下CLion配置说明CLion是C/C++的IDE,可以配置多种编译环境,本文以配置MinGW编译环境为例。安装CLion的安装可直接到官网下载ZIP,文件解压后直接运行即可。我在......
  • Camera | 5.Linux v4l2架构(基于rk3568)
    上一篇我们讲解了如何编写基于V4L2的应用程序编写,本文主要讲解内核中V4L2架构,以及一些最重要的结构体、注册函数。厂家在实现自己的摄像头控制器驱动时,总体上都遵循这个架......
  • Java关于栈(Stack)、队列(Queue)知识点拓展
    Stack类:Stack继承了Vector,而Vector类底层使用数组存储数据,Stack对象中存储的数据也是存储在数组中,常用方法:push(Edata):把数据压入栈addElement():是父类Vect......