我有如下的SQL查询
select * from Attachments a left join UserTickets ut on ut.Id=a.UserTicketId left join Tickets t on t.Id=ut.TicketId where a.ItemKey='abcd'
它在sql server中返回正确的结果,但是当我在linq中尝试我的mvc项目中的实体时,如下所示
var attachmentDetails = (from a in AttachmentsService.FindAllAttachments().Attachments join ut in UserTicketsService.FindAllUserTickets().UserTickets on a.UserTicketId equals ut.Id into aut from ut in aut.DefaultIfEmpty() join t in TicketsService.FindAllTickets().Tickets on ut.TicketId equals t.Id into utt from t in utt.DefaultIfEmpty() where a.ItemKey.ToUpper() == userName.ToUpper() select new UserTicketsViewModel { AttachmentId = a.Id, FilePath = a.FileName, TicketName=t!=null?t.TicketName:"", FileName = Path.GetFileName(a.FileName), UserId = UserId, }).ToList();
它在" ut.ticketId" .inner excetion show" null"。请提示我做错了
答案 0 :(得分:2)
请尝试以下查询。
var attachmentDetails = (from a in AttachmentsService.FindAllAttachments().Attachments
join ut in UserTicketsService.FindAllUserTickets().UserTickets on a.UserTicketId==null ? 0 : a.UserTicketId equals ut.Id into aut
from ut in aut.DefaultIfEmpty()
join t in TicketsService.FindAllTickets().Tickets on ut.TicketId==null ? 0 : ut.TicketId equals t.Id into utt
from t in utt.DefaultIfEmpty()
where a.ItemKey.ToUpper() == userName.ToUpper()
select new UserTicketsViewModel
{
AttachmentId = a.Id,
FilePath = a.FileName,
TicketName=t!=null?t.TicketName:"",
FileName = Path.GetFileName(a.FileName),
UserId = UserId,
}).ToList();
答案 1 :(得分:0)
我认为问题在于LINQ正在尝试将所有内容转换为SQL(包括Path.GetFileName方法)。尝试将此查询作为:
运行var attachmentDetails = (from a in AttachmentsService.FindAllAttachments().Attachments
join ut in UserTicketsService.FindAllUserTickets().UserTickets on a.UserTicketId equals ut.Id into aut
from ut in aut.DefaultIfEmpty()
join t in TicketsService.FindAllTickets().Tickets on ut.TicketId equals t.Id into utt
from t in utt.DefaultIfEmpty()
where a.ItemKey.ToUpper() == userName.ToUpper()
select new UserTicketsViewModel
{
AttachmentId = a.Id,
FilePath = a.FileName,
TicketName=t!=null?t.TicketName:"",
FileName = a.FileName,
UserId = UserId,
}).ToList();
foreach (var item in attachmentDetails)
item.FileName = Path.GetFileName(item.FileName);