Linq中的case语句可以为null的datetime字段

时间:2016-09-29 07:19:57

标签: c# linq

我有可查询数据时间字段的linq查询,该字段根据条件填充值。

class SocialFeedCreateAPIView(CreateAPIView):
    queryset = SocialFeed.objects.all()
    serializer_class = SocialFeedCreateSerializer

    def initial(self, request, *args, **kwargs):
        # or any other condition you want
        if self.request.method.lower() == 'post':
            data = self.request.data
            # manipulate it 
            data['foo'] = 'foo'
            request._request.POST = data
        return super(SocialFeedCreateAPIView, self).initial(request, *args, **kwargs)

这里DateCompleted可以为空。如果状态成功那么我只需要完成日期。另外我需要将它显示为null。现在“:Null”部分抛出错误。

提前致谢 李苏滨

3 个答案:

答案 0 :(得分:5)

试试这个

var result=(from t1 in context.table1
             join t2 in context.table2 
            on t1.id equals t2.fieldId
            select new model1
            {
             name= t2.name,
             DateCompleted = t1.Status == "Success" ? Convert.ToDateTime(t1.CompletedDate): (DateTime?)null
                                                           }).ToList();

答案 1 :(得分:3)

请尝试以下代码:

var result=(from t1 in context.table1
            join t2 in context.table2 
            on t1.id equals t2.fieldId
            select new model1
            {
                name= t2.name,
                DateCompleted = t1.Status == "Success" 
                    ? Convert.ToDateTime(t1.CompletedDate)
                    : (DateTime?) null
            }).ToList();

答案 2 :(得分:1)

您需要使用可为空的日期时间:默认(日期时间?)