.NET中好用的MongoDb ORM很少,选择也很少,所以我打造了一款适合SQL习惯的MongoDb ORM,让用户多一个选择。

1、 MongoDB ORM教程
1.1 NUGET 安装
SqlSugar.MongoDbCore
SqlSugarCore
1.2 已支持功能
单表CRUD+分页+排序+简单分组+嵌套文件(类似Json类型)+简单联表

1.3 创建DB对象
复制代码
//注册DLL防止找不到DLL(扔在程序启动时)
InstanceFactory.CustomAssemblies = new System.Reflection.Assembly[] {
typeof(SqlSugar.MongoDb.MongoDbProvider).Assembly };

//db对象(用法和sqlsugar入门中一样)
var db = new SqlSugarClient(new ConnectionConfig()
{
IsAutoCloseConnection = true,
DbType = DbType.MongoDb,
ConnectionString = SqlSugarConnectionString

},
it =>
{
it.Aop.OnLogExecuting = (sql, para) =>
{ //AOP打印SQL
Console.WriteLine(UtilMethods.GetNativeSql(sql, para));
};
});


//字符串2种都可以
var ConnectionString = "mongodb://root:123456@222.71.212.3:27017/testDB?authSource=admin";
var ConnectionString = "host=222.71.212.3;Port=27017;Database=testDB;Username= root;Password=123456;authSource=admin;replicaSet=";
复制代码

1.4 实体类定义(重点注意)
主键定义:继承MongoDbBase里面自定义好了主键

外键定义 :设置 ColumnDataType =nameof(ObjectId)

复制代码
//继承的MongoDbBase里面已经有了主键,当然你也可以复制出来不用基类
public class Student:MongoDbBase
{
//主键在基类,也可以自个复制出来不用基类
public string Name { get; set; }

//外键需要设置ObjectId类型不然存储会的是string
[SqlSugar.SugarColumn(ColumnDataType =nameof(ObjectId))]
public string SchoolId { get; set; }
}


//MongoDbBase是ORM自带的一个类,方便你不定义主键
public class MongoDbBase
{
[SugarColumn(IsPrimaryKey = true, IsOnlyIgnoreInsert = true, ColumnName = "_id")]
public string Id { get; set; }
}
复制代码
2、CRUD用例
2.1 插入
复制代码
//插入无返回值
db.Insertable(data).ExecuteCommand();

//插入并将主键赋值到实体
db.Insertable(data).ExecuteCommandIdentityIntoEntity();

//插入返回IDS
var ids= db.Insertable(data).ExecuteReturnPkList<string>();
复制代码
2.2 查询
MongoDb一般是单表操作比较多,官方并不推荐联表操作一般用json做嵌套文档比较多

不过SqlSugar也支持了联表

复制代码
//简单查询
var data2 = db.Queryable<Student>().Where(it => it.Book.Price == 1).ToList();

//分页
var count = 0;
var list = db.Queryable<School>().OrderBy(it=>it.Name).ToPageList(1,2,ref count);

//json类型(实体定义isjson)
var data2 = db.Queryable<Student>().Where(it => it.Book.Price == 1).ToList();

//简单联表(目前只能支持这种基本联表)
var list = db.Queryable<Student>()
.LeftJoin<School>((x, y) => x.SchoolId == y.Id)
.LeftJoin<School>((x, y, z) => x.SchoolId == z.Id)
.Where((x, y) =>y.Name == "TestSchool")
.Select((x, y,z) => new
{
StudentName = x.Name,
SchoolName = y.Name,
SchoolName2=z.Name
}).ToList();

//简单分组查询
var list14 = db.Queryable<OrderInfo>()
.GroupBy(it => new { it.Name ,it.Price })
.Select(it => new
{
key = it.Name,
Prie=it.Price,
groupCount = SqlFunc.AggregateCount(it.Id),
max = SqlFunc.AggregateMax(it.Id),
min = SqlFunc.AggregateMin(it.Id)
}).ToList();

//目前不支持导航查询和子查询
复制代码
2.3 删除
//根据主键岀队string [] ids= [...]
db.Deleteable<Student>().In(ids).ExecuteCommandAsync()
//根据实体删除,实体要有主键 var delrow = db.Deleteable(data).ExecuteCommand();
2.4 更新
复制代码
var updateRow2 = db.Updateable(new List<OrderInfo>()
{
new OrderInfo() { Id = ids.First(),Name="a31",Price=11},
new OrderInfo() { Id = ids.Last(),Name="a41"}
})
.ExecuteCommand();

var updateRow3= db.Updateable<OrderInfo>()
.SetColumns(it=>it.Name=="xx")
.Where(it=> it.Id == id)
.ExecuteCommand();
复制代码
2.5 使用原生SQL
复制代码
db.Ado.ExecuteCommand(@"insertMany UnitSchool123131 [{ ""Name"" : ""XX大学"" }]");
//C#对象构造
var documents = new[]
{
new BsonDocument { { "Name", "XX大学" } }
};
var bsonArray = new BsonArray(documents).ToJson();
var cmd = $"insertMany UnitSchool123131 {json}";
db.Ado.ExecuteCommand(cmd);
//查询
var list=db.Ado.SqlQuery<T>(cmd);
var dt=db.Ado.GetDataTable(cmd);
//sqlsugar中获取原生对象
IMongoDatabase rdb= ((MongoDbConnection)db.Ado.Connection).GetDatabase();
//IMongoDatabase 是什么东西?
//var client = new MongoClient("mongodb://localhost:27017");
//IMongoDatabase database = client.GetDatabase("TestDatabase");
复制代码

3、源码DEM
https://github.com/DotNetNext/SqlSugar

DEMO 下载 : https://github.com/DotNetNext/SqlSugar