将SQLServer sql转换为Linq

时间:2016-06-20 02:05:39

标签: c# asp.net sql-server entity-framework linq

我有一个SQL来查看表主和详细信息。如何转换为linq。请帮帮我:

Select B.idchatuser,B.Nama, B.Hp,
(select TOP 1 CreatedTime from ChatUserConversation 
where IdChatUser = B.IdChatUser order by CreatedTime) CreatedTime
from ChatUser B 
order by CreatedTime desc

2 个答案:

答案 0 :(得分:2)

这个怎么样?

from B in ChatUser
join C in ChatUserConversation on B.IdChatUser equals C.IdChatUser
group new {B,C} by new {B.IdChatUser, B.Nama, B.Hp} into g
let CreatedTime = g.OrderBy(x=>x.C.CreatedTime).Select(x=>x.C.CreatedTime).FirstOrDefault()
orderby CreatedTime descending
select new 
{
    IdChatUser = g.Key.IdChatUser, 
    Nama = g.Key.Nama, 
    Hp = g.Key.Hp, 
    CreatedTime = CreatedTime
}

答案 1 :(得分:1)

假设您拥有ChatUserChatUserConversation C#个实体,则可以执行此操作。

var results = ChatUser.Select(x=> new 
         {
             x.idchatuser,
             x.Name,
             x.Hp,
             CreatedTime =  ChatUserConversation .Where(c=> c.IdChatUser = x.IdChatUser)
                                                 .Max(c=>c.CreatedTime)  
         })
        .ToList();