这句linq语句应该怎么写?

seven7676 2016-05-25 01:25:54
我想把一句sql语句转换为linq语句。

sql语句:


select
*
from activity
where 1=1
<if test="city != null and city!=''">
and city =#{city,jdbcType=VARCHAR}
</if>

<if test="contentType != null and contentType >0">
and content_type =#{contentType,jdbcType=INTEGER}
</if>
limit #{start,jdbcType=INTEGER},#{limit,jdbcType=INTEGER}



这句sql语句的基本意思是:当字段city不为null,并且不为空值时将字段city 作为查询条件。当字段contentType 不为null,并且不为空值时,将字段contentType作为查询条件。

最后一句的意思好像是分页的意思。

请问这句sql语句应该如何转换为linq语句?
...全文
276 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
龍过鸡年 2016-06-12
  • 打赏
  • 举报
回复


var result = db.Activity.ToArray() // 记得使用 string.IsNullOrWhiteSpace 前需要先把数据获取到本地否则会报错
    .OrderBy(o => o.property) // 确保分页的结果是正确的
    .Where(w => w.status == 1)
    .Where(w => !string.IsNullOrWhiteSpace(w.city))
    .Where(w => (w.contentType ?? 0) > 0)
    .Skip(pageCount * pageIndex).Take(pageCount)
    .AsEnumerable(); // 只读列表

正怒月神 2016-06-01
  • 打赏
  • 举报
回复
就是1楼的写法了。 var q=....... if(...) q=q.where(..) if(...) q=q.where(..) return q.tolist() 这个格式
  • 打赏
  • 举报
回复
var query = db.Activity.Where(a=>a.Status =1);
seven7676 2016-05-25
  • 打赏
  • 举报
回复
引用 1 楼 starfd 的回复:
这是mysql,然后看语法类似ibatis,做的是分页 换成linq的话类似下面
var query = db.Activity;
if (!string.IsNullOrWhiteSpace(city))
{
    query = query.Where(a => a.City == city);
}
if (contentType > 0)
{
    query = query.Where(a => a.ContentType = contentType);
}
return query.Skip(start).Take(limit).ToList();
不好意思,少了条件。


select 
    *
    from activity
    where 1=1
    <if test="city != null and city!=''">
     and city =#{city,jdbcType=VARCHAR}
    </if>
    
    <if test="contentType != null and contentType >0">
     and content_type =#{contentType,jdbcType=INTEGER}
    </if>
     and status =1
    order by create_time desc
    limit #{start,jdbcType=INTEGER},#{limit,jdbcType=INTEGER}

那么用linq语句写,应该怎么写啊?
  • 打赏
  • 举报
回复
这是mysql,然后看语法类似ibatis,做的是分页 换成linq的话类似下面
var query = db.Activity;
if (!string.IsNullOrWhiteSpace(city))
{
    query = query.Where(a => a.City == city);
}
if (contentType > 0)
{
    query = query.Where(a => a.ContentType = contentType);
}
return query.Skip(start).Take(limit).ToList();

8,497

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 LINQ
社区管理员
  • LINQ
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧