用习惯Linq2Sql的盆友肯定对 from... where....select 这种inline式,强类型的 写法大爱不已.
可惜我不是,对于表关联, 这种写法及其最终sql 分析都非常 egg疼, 于是乎Dapper作者博客里就有不少将原Linq2sql 转 sql dapper的心得.
但是,我完全同意: 在一般简单查询,Lambda写起来更顺手,更美观,更强类型. (Lambda解析转SQL语句,请看这里)
所以我的Dappers 里 又加了个接口. 所有这些,都是面向sql, 面向跨oracle / sql server 的.
1. 如果彻底不写SQL, 数据库的基本信息还是需要的
[System.Data.Linq.Mapping.Table(Name = "SYS_OFFICE")]
public class MyOffice
{
[System.Data.Linq.Mapping.Column(Name = "OfficeId", IsPrimaryKey = true)]
public string Id { get; set; }
public string Name { get; set; }
public string OfficeType { get; set; }
......
public class MyOffice
{
[System.Data.Linq.Mapping.Column(Name = "OfficeId", IsPrimaryKey = true)]
public string Id { get; set; }
public string Name { get; set; }
public string OfficeType { get; set; }
......
2. Query<T>(whereExpression)
var user = dao.Query<MyUser>(u => u.UserCode.StartsWith("chen"));//此时用到上述mapping,否则无需描述mapping
var user1 = dao.Query<MyUser,MyOffice>("select t.* from SYS_USER t inner join SYS_Office t1 on t.OfficeId=t1.Id",
(u,o) => u.UserCode.StartsWith("chen") && o.Name.Contains("办公室"));
var user2 = dao.Query<IDictionary,MyUser, MyOffice>("select t1.UserCode,t1.Name from SYS_USER t1 inner join SYS_Office t2 on t1.OfficeId=t2.Id",
(d,u, o) => u.UserCode.StartsWith("chen") && o.Name.Length>4);
var user1 = dao.Query<MyUser,MyOffice>("select t.* from SYS_USER t inner join SYS_Office t1 on t.OfficeId=t1.Id",
(u,o) => u.UserCode.StartsWith("chen") && o.Name.Contains("办公室"));
var user2 = dao.Query<IDictionary,MyUser, MyOffice>("select t1.UserCode,t1.Name from SYS_USER t1 inner join SYS_Office t2 on t1.OfficeId=t2.Id",
(d,u, o) => u.UserCode.StartsWith("chen") && o.Name.Length>4);
3.UnitTest result