安装mongodb数据库
官网下载地址 https://www.mongodb.com/download-center/community
网盘下载地址 链接:https://pan.baidu.com/s/1bhrEk0si4SkB0XX0Zyu5_Q 提取码:6rrt
安装mongodb管理工具
官网下载地址 https://robomongo.org/
网盘下载地址 链接:https://pan.baidu.com/s/1LVvid3Wce2x9k3CDPxmoag 提取码:4e4c
修改ET数据库配置信息:
1. 在Unity中修改信息 Tools - > 命令行配置
选择LocalAllServer.txt
2.修改Server的配置信息
在Server.APP中找到Program进入。
找到DBComponent鼠标移动上去按F12进入到定义
解除下方的注释
3.在Server中创建测试实体类
在Server.Model中创建一个自己的文件夹目录然后创建一个UserInfo的实体类继承自 Entity
UserInfo类内容
using MongoDB.Bson.Serialization.Attributes;
namespace ETModel
{
/// <summary>
/// 用户信息
/// </summary>
[BsonIgnoreExtraElements]
public class UserInfo : Entity
{
public string Account;
public string PassWord;
}
}
现在UserInfo已经创建完成,接下来就可以在自己所生成的接口中进行读写操作了。在ET中如果你想对数据库进行操作的话你需要先获得该组件!
DBProxyComponent dbProxy = Game.Scene.GetComponent<DBProxyComponent>();
查询数据:
该操作为查询所有账号为admin的数据如果查询成功则users的Count将大于0
List<ComponentWithId> users = await dbProxy.Query<UserInfo>(_user=>_user.Account == "admin");
在上一步如果我们如果长度大于0则表示查询成功我们可以使用ID来获取该条数据!
UserInfo user = await dbProxy.Query<UserInfo>(users[0].Id);
写入数据:
实例化一个类写入到数据库中
账号为admin密码为123456
UserInfo newUserInfo = ComponentFactory.Create<UserInfo>();
newUserInfo.Account = "admin";
newUserInfo.PassWord = "123456";
await dbProxy.Save(newUserInfo); //写入数据库
ET框架会为我们的数据库自动创建表所以我们不需要关心表的创建当我们写入数据后该表直接创建
删除数据:
在ET4.0中并未实现删除数据的功能,所以我们需要自己来写删除功能
选中F12到定义 在其中添加两个方法来做删除
public static async Task Delete<T>(this DBProxyComponent self,long id)
{
DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
await dbComponent.GetCollection(typeof(T).Name).DeleteOneAsync(i => i.Id == id);
}
public static async Task DeleteAll<T>(this DBProxyComponent self)
{
DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
var filter = Builders<ComponentWithId>.Filter.Empty;
await dbComponent.GetCollection(typeof(T).Name).DeleteManyAsync(filter);
}
Delete需要一个参数id 即为在数据库中的id DeleteAll 为删除该表的所有数据使用方法和之前的保存查询相同
调用该行代码会发现你的用户表被清空了。
删除单条数据就不做演示了, 通过查询获取到数据的ID然后通过delete方法就可以删除该条数据了。