5.x文档地址
http://www.donet5.com/Home/Doc
该方法可以让Lambda支持自定义解析, 可以把数据库的自带函数封装起来, 享受一个完美的ORM
当然, 该方法不仅仅只是支持查询里面使用, 对应的查询, 修改, 删除都可以使用自定义Lambda解析, 这里用查询做Demo
public class Demo
{
public static SqlSugarClient GetDb()
{
//Create ext method
var expMethods = new List<SqlFuncExternal>();
expMethods.Add(new SqlFuncExternal()
{
UniqueMethodName = "MyToString",
MethodValue = (expInfo, dbType, expContext) =>
{
if(dbtype=DbType.SqlServer)
return string.Format("CAST({0} AS VARCHAR(MAX))", expInfo.Args[0].MemberName);
else
throw new Exception("未实现")'
}
});
var config = new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
ConfigureExternalServices = new ConfigureExternalServices()
{
SqlFuncServices = expMethods//set ext method
}
};
SqlSugarClient db = new SqlSugarClient(config);
return db;
}
public static string MyToString<T>(T str)
{
throw new NotSupportedException("Can only be used in expressions");
}
public static void Init()
{
var db = GetDb();
var list = db.Queryable<Student>().Where(it => MyToString(it.Id) == "1302583").ToList();
var sql = db.Queryable<Student>().Where(it => MyToString(it.Id) == "1302583").ToSql();
//生成的Sql CAST([Id] AS VARCHAR(MAX))
Console.WriteLine(sql);
}
}2016 © donet5.comApache Licence 2.0