.netcore mysql_.netcore基于mysql的codefirst

.netcore基于mysql的codefirst

此文仅是对于netcore基于mysql的简单的codefirst实现的简单记录。示例为客服系统消息模板的增删改查实现

第一步、创建实体项目,并在其中建立对应的实体类,以及数据库访问类

须引入Pomelo.EntityFrameworkCore.MySql和Microsoft.EntityFrameworkCore

///

///消息模板///

public classMessatgeTemplate

{///

///id///

[Key]public System.Guid Id { get; set; }///

///名称///

[MaxLength(250)]public string Name { get; set; }///

///关键字///

[MaxLength(500)]public string Keywords { get; set; }///

///内容///

public string Content { get; set; }///

///语言///

[MaxLength(80)]public string CultureCode { get; set; }///

///类别///

[MaxLength(250)]public string Category { get; set; }///

///备注信息///

public string Remark { get; set; }///

///是否启用///

public bool Enabled { get; set; }///

///创建时间///

public DateTime Created { get; set; }///

///最近修改时间///

public DateTime LastModified { get; set; }

}

///

///

///

public classCustomerServiceContext : DbContext

{public CustomerServiceContext(DbContextOptionsoptions)

:base(options)

{

}///

///配置///

///

protected override voidOnConfiguring(DbContextOptionsBuilder optionsBuilder)

{base.OnConfiguring(optionsBuilder);

}public virtual DbSet MessatgeTemplate { get; set; }

}

第二步、创建业务服务项目,添加对应的业务处理类

///

///客服业务统一接口///

public interfaceICustomerServicerSerice

{

}

///

///模板业务类///

public classMessageTemplateService : ICustomerServicerSerice

{privateCustomerServiceContext _CustomerServiceContext;publicMessageTemplateService(CustomerServiceContext customerServiceContext)

{this._CustomerServiceContext =customerServiceContext;

}///

///创建模板///

public voidCreateMessageTemplate()

{//todo create

}///

///修改模板///

public voidModifyMessageTemplate()

{//TODO modified

}///

///获取模板///

///

public ListGetMessageTemplate()

{//TODO根据传入参数查询模板

return null;

}///

///删除///

public voidDeleteMessageTemplate(Guid id)

{var template = _CustomerServiceContext.MessatgeTemplate.FirstOrDefault(p => p.Id ==id);if (template != null)

{

_CustomerServiceContext.MessatgeTemplate.Remove(template);

_CustomerServiceContext.SaveChanges();

}

}///

///批量设置是否可用///

///

///

public void BatchEnableTemplate(List ids, boolenabled)

{//TODO set enabled

}

}

第三步、创建webapi项目,并在其中建立对应的实体类,以及数据库访问类

须引入Microsoft.EntityFrameworkCore和Microsoft.EntityFrameworkCore.Design.

1、在appsettings.json中配置数据连接

"ConnectionStrings": {"CumstomerServiceConnection": "server=localhost;port=3306;database=CustomerServiceCenter;uid=root;pwd=root23456;CharSet=utf8"}

2、修改startup.cs类的ConfigureServices注入db访问类

services.AddDbContext(p => p.UseMySql(Configuration.GetConnectionString("CumstomerServiceConnection")));

3、设置该webapi项目为启动项目,在nuget程序包控制台选择第一步中创建的实体类项目依次运行如下脚本创建数据库

1)add-migration init

2) update-database

上面的两个命令中,add-migration表示添加数据迁移,其实就是将实体变更转换成sql(add-migraion后面的init只是个名称,可以自行定义),update-database是将生成的数据迁移信息更新到数据库

另外一些可能用到的命令

remove-migration  ---将最近生成的迁移(没有更新到数据库的)移除掉

script-migration --生成数据库迁移相应的脚本

------------------------

命令执行成功后,就可以在数据库中找到创建好的数据库和表了

821f97680989b87686b103b3486a9a30.png

script-datatable可以生成数据库脚本语句

a26f74de4085f123a4daeb05bdcc8f15.png

好了,以上就完成了codefirst的简单操作了。不过跟着第二步的业务类其实没啥关系!!!如果只是进行数据迁移确实没有service层什么事,但是业务逻辑要走通,实现crud,业务层还是必须的。

---------------------------------------------------------------------------------------------------------------------

以下就顺带写下controller中引入service,实现简单的删除业务逻辑(其它的业务逻辑---略)

在webapi创建MessageTemplateController

[Route("api/[controller]")]

[ApiController]public classMessageTemplateController : ControllerBase

{privateMessageTemplateService _MessageTemplateService;publicMessageTemplateController(MessageTemplateService messageTemplateService)

{this._MessageTemplateService =messageTemplateService;

}///

///删除///

///

[HttpPost("DeleteMessageTemplate")]public voidDeleteMessageTemplate(Guid id)

{

_MessageTemplateService.DeleteMessageTemplate(id);

}//TODO其他操作:查询,新增,修改等

}

修改Startup.cs类,注入服务

public voidConfigureServices(IServiceCollection services)

{

services.AddControllers();

services.AddDbContext(p => p.UseMySql(Configuration.GetConnectionString("CumstomerServiceConnection")));#region 注入业务服务Assembly assembly= Assembly.Load("Qingy.DotNetCoreStudy.CustomerServiceService");

List types = assembly.GetTypes().Where(u => u.IsClass && !u.IsAbstract && !u.IsGenericType&& u.GetInterfaces().Any(p => p == typeof(ICustomerServicerSerice))

).ToList();foreach (var item intypes)

{

services.AddTransient(item);

}#endregion}

综合以上,就可以将api到db的完整实现了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392573.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode 34. 在排序数组中查找元素的第一个和最后一个位置(二分查找)

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 如果数组中不存在目标值 target,返回 [-1, -1]。 进阶: 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗&#xff1…

CentOS6.7上使用FPM打包制作自己的rpm包

自定义rpm包,还是有逼格和实际生产环境的意义的。 (下面的文档有的代码由于博客排版的问题导致挤在了一起,需要自己判别) 安装FPM fpm是ruby写的,因此系统环境需要ruby,且ruby版本号大于1.8.5。 # 安装ruby模块 yum -y…

汉堡菜单_开发人员在编写汉堡菜单时犯的错误

汉堡菜单by Jared Tong汤杰(Jared Tong) 开发人员在编写汉堡菜单时犯的错误 (The mistake developers make when coding a hamburger menu) What do The New York Times’ developers get wrong about the hamburger menu, and what do Disney’s and Wikipedia’s get right?…

android 涨潮动画加载_Android附带涨潮动画效果的曲线报表绘制

写在前面本文属于部分原创,实现安卓平台正弦曲线类报表绘制功能介绍,基于网络已有的曲线报表绘制类(LineGraphicView)自己添加了涨潮的渐变动画算法最终效果图废话少说,直接上源码一、自定义View LineGraphicView,本类注释不算多&…

使用css3属性transition实现页面滚动

<!DOCTYPE html> <html><head><meta http-equiv"Content-type" content"text/html; charsetutf-8" /><title>慕课七夕主题</title><script src"http://libs.baidu.com/jquery/1.9.1/jquery.min.js">&…

leetcode 321. 拼接最大数(单调栈)

给定长度分别为 m 和 n 的两个数组&#xff0c;其元素由 0-9 构成&#xff0c;表示两个自然数各位上的数字。现在从这两个数组中选出 k (k < m n) 个数字拼接成一个新的数&#xff0c;要求从同一个数组中取出的数字保持其在原数组中的相对顺序。 求满足该条件的最大数。结…

Oracle Study之--Oracle等待事件(5)

Db file single write这个等待事件通常只发生在一种情况下&#xff0c;就是Oracle 更新数据文件头信息时&#xff08;比如发生Checkpoint&#xff09;。当这个等待事件很明显时&#xff0c;需要考虑是不是数据库中的数据文件数量太大&#xff0c;导致Oracle 需要花较长的时间来…

两台centos之间免密传输 scp

两台linux服务器之间免密scp&#xff0c;在A机器上向B远程拷贝文件 操作步骤&#xff1a;1、在A机器上&#xff0c;执行ssh-keygen -t rsa&#xff0c;一路按Enter&#xff0c;不需要输入任何内容。&#xff08;如有提示是否覆盖&#xff0c;可输入y后按回车&#xff09;2、到/…

jsp导出数据时离开页面_您应该在要离开的公司开始使用数据

jsp导出数据时离开页面If you’re new in data science, “doing data science” likely sounds like a big deal to you. You might think that you need meticulously collected data, all the tools for data science and a flawless knowledge before you can claim that y…

分步表单如何实现 html_HTML表格入门的分步指南

分步表单如何实现 htmlby Abhishek Jakhar通过阿比舍克贾卡(Abhishek Jakhar) HTML表格入门的分步指南 (A step-by-step guide to getting started with HTML tables) 总览 (Overview) The web is filled with information like football scores, cricket scores, lists of em…

laravel mysql pdo,更改Laravel中的基本PDO配置

My shared web host have some problems with query prepares and I want to enable PDOs emulated prepares, theres no option for this in the config\database.php.Is there any way I can do that in Laravel?解决方案You can add an "options" array to add o…

Java多线程-工具篇-BlockingQueue

Java多线程-工具篇-BlockingQueue 转载 http://www.cnblogs.com/jackyuj/archive/2010/11/24/1886553.html 这也是我们在多线程环境下&#xff0c;为什么需要BlockingQueue的原因。作为BlockingQueue的使用者&#xff0c;我们再也不需要关心什么时候需要阻塞线程&#xff0c;什…

leetcode 204. 计数质数

统计所有小于非负整数 n 的质数的数量。 示例 1&#xff1a; 输入&#xff1a;n 10 输出&#xff1a;4 解释&#xff1a;小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 解题思路 大于等于5的质数一定和6的倍数相邻。例如5和7&#xff0c;11和13,17和19等等&#xff1b…

JAVA 网络编程小记

在进行JAVA网络编程时&#xff0c;发现写入的数据对方等200ms左右才会收到。起初认为是JAVA自已进行了 Cache。进行flush也没有效果。查看JDK代码&#xff0c;Write操作直接调用的native方法&#xff0c;说明JAVA层面并没有缓存。再看flush&#xff0c;只是一个空方法. FileOut…

vue生成静态js文件_如何立即使用Vue.js生成静态网站

vue生成静态js文件by Ondřej Polesn通过OndřejPolesn 如何立即使用Vue.js生成静态网站 (How to generate a static website with Vue.js in no time) You have decided to build a static site, but where do you start? How do you select the right tool for the job wit…

查看文件夹大小的4种方法,总有一种是你喜欢的

有必要检查文件夹的大小,以确定它们是否占用了太多的存储空间。此外,如果你通过互联网或其他存储设备传输文件夹,还需要查看文件夹大小。 幸运的是,在Windows设备上查看文件夹大小非常容易。窗口中提供了图形化和基于命令行的应用程序,为你提供了多种方法。 如何在Windo…

Python 获取服务器的CPU个数

在使用gunicorn时&#xff0c;需要设置workers&#xff0c; 例如&#xff1a; gunicorn --workers3 app:app -b 0.0.0.0:9000 其中&#xff0c;worker的数量并不是越多越好&#xff0c;推荐值是CPU的个数x21&#xff0c; CPU个数使用如下的方式获取&#xff1a; python -c impo…

多种数据库连接工具_20多种热门数据工具及其不具备的功能

多种数据库连接工具In the past few months, the data ecosystem has continued to burgeon as some parts of the stack consolidate and as new challenges arise. Our first attempt to help stakeholders navigate this ecosystem highlighted 25 Hot New Data Tools and W…

怎么连接 mysql_怎样连接连接数据库

这个博客是为了说明怎么连接数据库第一步&#xff1a;肯定是要下载数据库&#xff0c;本人用的SqlServer2008&#xff0c;是从别人的U盘中拷来的。第二步&#xff1a;数据库的登录方式设置为混合登录&#xff0c;步骤如下&#xff1a;1.打开数据库这是数据库界面&#xff0c;要…

webstorm环境安装配置(less+autoprefixer)

node安装&#xff1a; 参考地址&#xff1a;http://www.runoob.com/nodejs/nodejs-install-setup.html 1.下载node安装包并完成安装 2.在开始菜单打开node 3.查看是否安装完成&#xff08;npm是node自带安装的&#xff09; 命令&#xff1a;node -v npm -v less安装&#xff1a…