问题的引出:
如下使用CASE的SQL如何用LINQ TO SQL 来实现呢?
select updateagaintime=( case when updateagaintime is null then begintime else updateagaintime end ) |
from workplan |
熟悉LINQ的很快会写出这样的语句:
IQueryable<workplan> result = from w in dataContext.workplan |
select new workplan |
{ |
updateagaintime = w.updateagaintime == null ? w.begintime : w.updateagaintime |
}; |
var viewData = new MyDataView |
{ |
workPlanPageDataView = result.ToList().ToPagedList(pageIndex, pageSize) |
}; |
上面的用法报错“不允许在查询中显式构造实体类型”(其中ToPagedList方法参见链接:参考>>“ASP.NET MVC 分页”)。
换了老赵的方法:http://jeffz.blog.51cto.com/309226/62391
代码如下(LINQ中使用SQL):
MyProjectDataContext dataContext = new MyProjectDataContext(); dataContext.Connection.Open(); SqlCommand command = new SqlCommand( @"SELECT [workplanid], [requirementid], [statusname], [endtime], [sellerid], [begintime], [technicianid], [updateagaintime]=(CASE WHEN [updateagaintime] IS NULL THEN [begintime] ELSE [updateagaintime] END), [difftime], [assitantsellerid], [remark], [isdeleted], [createtime], [createby], [updateby], [groupid]" + @"FROM [workplan] ORDER BY [updateagaintime] DESC", (SqlConnection)dataContext.Connection); using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { result = dataContext.Translate<workplan>(reader).AsQueryable<workplan>(); }
将结果集改为List<workplan>类型,即ToList<workplan>()之后问题解决。
相关帖子:http://topic.csdn.net/u/20100721/19/8c6d35ff-93c5-44b0-bcce-bd6712dcbe62.html
本文首发于我的博客园博客