将T-SQL语句转换为LINQ表达式

时间:2017-03-28 19:32:56

标签: c# sql linq linq-to-sql linq-to-entities

我对linq很新,并且实际上正在努力将以下t-sql语句转换为linq to sql或linq to entities表达式:

([FromBody] dynamic formObj, string type)

2 个答案:

答案 0 :(得分:1)

试试这个,不能测试

        var firstItem = (
                        from vmm in db.VotingMatrixMember
                        join vm in db.VotingMatrix on vmm.VotingMatrixID equals vm.ID
                        where vm.EventID =  "abbe3077-24de-45d8-ac04-13dba97c1567"
                                                && vm.Deleted = 0
                                                && vmm.Deleted = 0
                        group new {vm, vmm} by new {vm.EventID, vmm.VotingMatrixID} into gr
                        select new
                        {
                            EventID = gr.Key.EventID,
                            VotingMatrixID = gr.Key.VotingMatrixID,
                            PersonAcceptedCount = gr.Sum(x => Convert.ToInt32(x.IsAccepted))
                        } 
                        into groupedItem 
                        orderby  groupedItem.PersonAcceptedCount descending 
                        select groupedItem                            
                         ).FirstOrDefault();

答案 1 :(得分:0)

var query =
  from vm in dataContext.VotingMatrices
  where vm.EventId == eventId
  where vm.Deleted == 0
  from vmm in vm.VotingMatrixMembers
  where vmm.Deleted == 0
  group vmm by new { vm.EventId, vmm.VotingMatrixId } into g
  select new
  {
    g.Key.EventId,
    g.Key.VotingMatrixId,
    PersonAcceptedCount: g.Select(x => Convert.ToInt32(x.IsAccepted)).Sum()
  } into resultRow
  order by resultRow.PersonAcceptedCount descending
  select resultRow;

var row = query.FirstOrDefault();