场景:有TableA,TableB两个表,需要联接两个表输出查询结果。以TableB为主表,链接TableA,查询时需要使用TableA中的字段作为查询条件。
加入有如下TableA,TableB表结构
//表A类
public class TableA{
public int id {get;set;}
public string name {get;set;}
public string value {get;set;}
}
//表B类
public class TableB{
public int id {get;set;}
public int table_a_id{get;set;}
public string name{get;set;}
public string title{get;set;}
}
//表B视图类
public class ViewTableB:TableB{
public string name_a {get;set;}
public string value_a {get;set;}
}
查询代码
string selectValue = "";//查询值
//Db为SqlSugarScopeProvider的实例
var queryView = Db.Queryable<TableB, TableA>((a, b) => new JoinQueryInfos(
JoinType.Left, a.table_a_id == b.id
))
.Select((a, b) => new ViewTableB()
{
id = a.id.SelectAll(),
name_a = b.name,
value_a = b.value
});
//查询时使用CopyNew新建实例查询,避免实例冲突报错
var query = Db.CopyNew().Queryable(queryView).Select<ViewTableB>();
if (!string.IsNullOrEmpty(selectValue)) {
query = query.Where(a => a.value_a.Contains(selectValue));
}
代码等价于SQL
select * from (
select a.*,b.name as name_a,b.value as value_a from TableB a
left join TableA b on a.table_a_id = b.id
) where value_a like concat('%',selectValue,'%')
注意:如果只用一次查询,则会报错,提示查询语句中不存在该列
string selectValue = "";//查询值
//Db为SqlSugarScopeProvider的实例
var query = Db.Queryable<TableB, TableA>((a, b) => new JoinQueryInfos(
JoinType.Left, a.table_a_id == b.id
))
.Select((a, b) => new ViewTableB()
{
id = a.id.SelectAll(),
name_a = b.name,
value_a = b.value
});
if (!string.IsNullOrEmpty(selectValue)) {
query = query.Where(a => a.value_a.Contains(selectValue));
}
//等价SQL
select a.* from TableB a
left join TableA b on a.table_a_id = b.id
where value_a like concat('%',selectValue,'%')
即在生成SQL语句时,不会带着TableA的列,引起该问题的具体原因未知,仅通过跟踪代码发现该问题,可能为sqlsugar框架问题