SqlSugar 拥有最强的 Mongodb 的功能支持, 表达式解析是目前所有ORM最强的
如果有新的需求我也会尽最大努力第一时间支持。
SqlSugar.MongoDbCore SqlSugarCore
单表CRUD、简单联表 、分页、排序、简单分组、嵌套文件(类似Json类型)
非对象方式更新、非对象方式删除、事务、插入或者更新
不支持功能:子查询和导航查询
//注册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) =>
{
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=";主键定义:继承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自带的一个类,方便你不定义主键
publicclass MongoDbBase
{
[SugarColumn(IsPrimaryKey = true, IsOnlyIgnoreInsert = true, ColumnName = "_id")]
public string Id { get; set; }
}
//常用特性说明
[SugarColumn(IsIgnore = true)]//忽略这列不处理
[SugarColumn(ColumnName ="Name")]//属性名和列名不一样可以设置列名
[SugarColumn(IsJson= true)] //标识是不是子对象//插入无返回值 db.Insertable(data).ExecuteCommand(); //插入并将主键赋值到实体 db.Insertable(data).ExecuteCommandIdentityIntoEntity(); //插入返回IDS var ids= db.Insertable(data).ExecuteReturnPkList<string>();
MongoDb一般是单表操作比较多,官方并不推荐联表操作一般用json做嵌套文档比较多
不过SqlSugar也支持了联表
//简单查询
var data2 = db.Queryable<Student>().Where(it => it.Num == 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();
//目前不支持导航查询和子查询//根据主键岀队 string [] ids= [...] db.Deleteable<Student>().In(ids).ExecuteCommandAsync() //根据实体删除,实体要有主键 var delrow = db.Deleteable(data).ExecuteCommand();
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();参数说明
//参数必须是一个完整的对象
db.表名.update({ "filter" : {...}, "update" : { "$set" : {.. } }) //其中参数是一个标准的对象
//错误写法
db.表名.update(参数1,参数2)//把filter和update去掉了变成了2个参数这种ORM不支持,orm只能解析一个参数重载SQL用例:
db.Ado.ExecuteCommand(@"db.table100.insertMany([{ ""Name"" : ""XX大学"" }])");
//C#对象构造
var documents = new[]
{
new BsonDocument { { "Name", "XX大学" } }
};
var json = new BsonArray(documents).ToJson();
var cmd = $"db.table100.insertMany({json})";
db.Ado.ExecuteCommand(cmd);
//查询
var list=db.Ado.SqlQuery<T>(cmd);
var dt=db.Ado.GetDataTable(cmd);
//写入操作
db.Ado.ExecuteCommand(cmd);
//sqlsugar中获取原生对象
IMongoDatabase rdb= ((MongoDbConnection)db.Ado.Connection).GetDatabase();
//IMongoDatabase 是什么东西?
//var client = new MongoClient("mongodb://localhost:27017");
//IMongoDatabase database = client.GetDatabase("TestDatabase");
[SqlSugar.SugarColumn(IsJson = true)]
public Book Book { get; set; }
var data2 = db.Queryable<Student>().Where(it => it.Book.Price == 1).ToList();
//子对象如果用到了ObjectId需要配置序列化
public class Book
{
[BsonRepresentation(BsonType.ObjectId)]//比普通类多个序列化ObjectId
[SqlSugar.SugarColumn(ColumnDataType = nameof(ObjectId))]
public string SchoolId{get;set;}
public decimal Price{ get; set;}
}SqlSugar.MongoDbCore 5.1.4.210 +版本支持
public class Book : MongoDbBase
{
public int Price{get;set;}
//json集合里面的外键需序列化成ObjectId
[BsonRepresentation(BsonType.ObjectId)]
[SqlSugar.SugarColumn(ColumnDataType = nameof(ObjectId))]
public string SchoolId{get;set;}
}
public class Student : MongoDbBase
{
public string Name { get; set; }
[SqlSugar.SugarColumn(IsJson = true)]
public Books Book { get; set; }
}
db.Queryable<Student>().Where(it => it.Books.Any(s => s.Price == 21)).ToList() [SugarColumn(IsJson = true)]
public List<string> Ids { get; set; }
var list2=db.Queryable<IdsModel>().Where(it => it.Ids.Contains(id)).ToList();var str="mongodb://root:123456@117.72.212.3:27017,117.72.212.4:27017,117.72.212.5:27017/testDB?authSource=admin&replicaSet=rs0"; //117.72.212.3:27017,117.72.212.4:27017,...:多个 MongoDB 节点地址。 //testDB:你要连接的数据库。 //authSource=admin:认证数据库是 admin。 //replicaSet=rs0:副本集名称必须写对(和你 MongoDB 实际副本集名字一致)。
public class MongoDbBase //ORM自带的基类
{
[BsonRepresentation(BsonType.ObjectId)]
[SugarColumn(IsPrimaryKey =true,IsOnlyIgnoreInsert =true,ColumnName ="_id")]
public string Id { get; set; }//ObjectId类型存储
}
public class MongoDbBaseLong//ORM自带的基类 SqlSugar.MongoDbCore 5.1.4.227+
{
[SqlSugar.SugarColumn(IsPrimaryKey = true, ColumnName = "_id")]
public long Id { get; set; }//long类型可以用sqlsugar雪花ID插入
}
public class MongoDbBaseString//ORM自带的基类 SqlSugar.MongoDbCore 5.1.4.227+
{
[SqlSugar.SugarColumn(IsPrimaryKey = true, ColumnName = "_id")]
public string Id { get; set; } //自定义string格式主键
}
public class MongoDbBaseGuid//ORM自带的基类 SqlSugar.MongoDbCore 5.1.4.227+
{
[SqlSugar.SugarColumn(IsPrimaryKey = true, ColumnName = "_id")]
public Guid Id { get; set; } //自定义guid类型主键
}版本号求:SqlSugar.MongoDbCore 5.1.4.232
var list= db.Queryable<object>().AS("TableName")
.OrderBy("{ \"Name\" : 1 }").Where("{ Age: 1 }").ToDataTable();如果要支持mongo事务,mongo得部署成副本集才行
把密码中的 @ 替换为 %40
//需要数据库支持事务配置
db.Insertable(list).PageSize(50).ExecuteCommand();
//无需数据库支持事务配置
db.Utilities.PageEach(list,50, pageList => {
db.Insertable(pageList).ExecuteCommand();//更新等都可以用
});https://github.com/DotNetNext/SqlSugar

2016 © donet5.comApache Licence 2.0