更新linq查询结果

时间:2017-12-21 18:01:13

标签: c# linq

以下代码在Users表上有一个联接(错误),它只提供AssignedUserId不是null的记录。我需要Request中的所有记录,无论AssignerUserId如何,然后在User.Name不是AssignedUserId时添加null

var query = from r in _context.Request
    join st in _context.ServiceType on r.ServiceTypeId equals st.ServiceTypeId
    join u in _context.Users on r.UserId equals u.UserId
    select new RequestDto
    {
        RequestId = r.RequestId,
        UserId = r.UserId,
        FirstName = r.FirstName,
        //...
        ServiceType = st.ServiceName,
        AssignedUserId = r.AssignedUserId,
        AssignedUser = u.Name
    };

return query.ToList();

如何仅针对User.Name不是AssignedUserId的记录获取null

3 个答案:

答案 0 :(得分:1)

你想要的是一个左连接 - 从请求中检索数据但只在可能的情况下加入Users表:

var query = from r in _context.Request
    join st in _context.ServiceType on r.ServiceTypeId equals st.ServiceTypeId
    join u in _context.Users on r.AssignedUserId equals u.UserId into ju
    from u in ju.DefaultIfEmpty()
    select new RequestDto
    {
        // ....
        AssignedUserId = r.AssignedUserId,
        AssignedUser = u?.Name
    };

至于评论中的例外情况,请参阅an expression tree lambda may not contain a null propagating operator

u.Name替换为u == null ? null : u.Name

答案 1 :(得分:0)

您想要执行left join

        var query = from r in _context.Request
            join st in _context.ServiceType on r.ServiceTypeId equals st.ServiceTypeId
            join u in _context.Users on r.AssignedUserId equals u.UserId into ps
            from u in ps.DefaultIfEmpty()
            select new RequestDto
            {
                RequestId = r.RequestId,
                UserId = r.UserId,
                FirstName = r.FirstName,
                ServiceType = st.ServiceName,
                AssignedUserId = r.AssignedUserId,
                AssignedUser = u?.Name
            };

我假设Users条件的加入是"r.AssignedUserId“。此外,最好使用导航属性而不是手动连接。

答案 2 :(得分:-1)

尝试

AssignedUser = r.AssignedUserId == null ? null : u.Name

如果您不希望AssignedUser成为null,则可以将其设置为String.Empty