开始实战
在上几篇文章中,配置好了网关。接下来就需要去请求接口了,请求接口得连接数据库,于是本篇文章就开始讲一下如何在.NET5中用EFCore连接Mysql数据库。
咱们以用户服务举例,首先安装两个Nuget包。
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.4" />
<PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.0" />
然后在appsetting.json中配置好数据库连接字符串。
"ConnectionStrings": {
"MysqlConnectionString": "server=localhost;port=3306;database=easyshop;uid=root;password=1234;CharSet=utf8" //my sql
},
接着在项目EasyShop.UserService
下新建一个数据库上下文的类叫MySqlDBContext.cs
,代码如下。
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EasyShop.UserService.Repository.Domain;
namespace EasyShop.UserService
{
public partial class MySqlDBContext:DbContext
{
public MySqlDBContext(DbContextOptions<MySqlDBContext> options)
: base(options)
{
}
public DbSet<User> User { set; get; }
}
}
由于当前是用户服务,目前也仅需要一个用户表,所以这里只写了一个User
的实体类。User.cs
,在Repository.Domain文件夹下,代码如下。
using EasyShop.UserService.Repository.Core;
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace EasyShop.UserService.Repository.Domain
{
[Table("user")]
/// <summary>
/// 用户实体
/// </summary>
public class User:Entity
{
/// <summary>
/// 用户昵称
/// </summary>
[Column("UserName")]
public string UserName { get; set; }
/// <summary>
/// 用户密码
/// </summary>
[Column("Password")]
public string Password { get; set; }
/// <summary>
/// 注册时间
/// </summary>
[Column("CreateTime")]
public DateTime CreateTime { get; set; }
}
}
继承自:Entity
,其实Entity.cs
里就一个Id,代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace EasyShop.UserService.Repository.Core
{
public class Entity
{
[Column("Id")]
public string Id { get; set; }
}
}
然后需要在Startup.cs
中的ConfigureServices
方法中引用Mysql
services.AddDbContext<MySqlDBContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("MysqlConnectionString")));
到目前为止就基本配置好了,接下来只要在需要查询数据的地方,注入进去数据库上下文类MySqlDBContext
,就可以查询数据了。
比如需要在一个类中的查询用户信息。
private readonly MySqlDBContext _mySqlDBContext;
public UserApp(MySqlDBContext mySqlDBContext)
{
_mySqlDBContext = mySqlDBContext;
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public UserView Get(string id)
{
var user = _mySqlDBContext.User.Where(c => c.Id == id).FirstOrDefault();
var userView = user.MapTo<UserView>();
return userView;
}
项目地址:https://gitee.com/limeng66/easy-shop