必须在Sub Query中声明Linq匿名类型成员

时间:2015-01-31 10:30:20

标签: c# sql-server linq

我正在尝试将this SQL查询转换为Linq,以在asp MVC中的View中返回,

Linq的预期输出:

TotalPoints Name

  231       John 

我在第二个选择新的子查询中收到此错误:

  

无效的表达式术语'。'

     

无效的匿名类型成员声明符。匿名类型成员必须   声明成员作业,简单名称或成员访问权。

到目前为止,

Linq查询:

public ActionResult UserTotal()
        {
            List<TotalPointsUser> onetotal = from t in (
    (from LoyaltyDetailsTable in dbpoints.LoyaltyDetailsTable
    where
      LoyaltyDetailsTable.CustomerTable.CustomerId == 1
    group new {LoyaltyDetailsTable.CustomerTable, LoyaltyDetailsTable.LoayaltyPointsTable} by new {
      LoyaltyDetailsTable.CustomerTable.Name,
      LoyaltyPointsId = LoyaltyDetailsTable.LoayaltyPointsTable.LoyaltyPointsId,
      Points = LoyaltyDetailsTable.LoayaltyPointsTable.Points,
      CustomerId = LoyaltyDetailsTable.CustomerTable.CustomerId
    } into g
    select new TotalPointsUser{
      CustomerId = 
      g.Key.LoyaltyPointsId == 4 ? 
        (from RedeemPointsTable in dbpoints.RedeemPointsTable
        where
          RedeemPointsTable.CustomerId == 1
        select new {
          RedeemPointsTable.Amount
        }).Count(p => p.Amount != null) : g.Count(p => p.CustomerTable.CustomerId != null),
      Name=g.Key.Name,
      Points = 
      g.Key.LoyaltyPointsId == 4 ? (
        (from RedeemPointsTable in dbpoints.RedeemPointsTable
        where
         RedeemPointsTable.CustomerId == 1
        select new {
         RedeemPointsTable.Amount
        }).Sum(p => p.Amount) * g.Key.Points) : g.Sum(p => p.LoayaltyPointsTable.Points)
    }))
select new {
  CustomerId = t.Sum(p => p.CustomerId),        // here is the error
  Points= t.Sum(p => p.Points),                // and here
  Name = 
    ((from CustomerTable in dbpoints.CustomerTable
    where
      CustomerTable.CustomerId == 1
    select new {
      CustomerTable.Name
    }).First().Name)
}
           .ToList();
            return View(onetotal);
}

模特课程:

public class TotalPointsUser
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public int Points { get; set; }
}

我是linq的新手,我可以知道必须做出哪些改变吗?

Ant帮助会很棒。

1 个答案:

答案 0 :(得分:1)

您的查询结构是:

from t in (
)
select new {
  Column1 = .Sum(p => p.TotalUserActions),        // here is the error
  Column2 = .Sum(p => p.AllTotalPoints),    // and here
}

您必须在结果中使用t别名,如下所示:

from t in (
)
select new {
  Column1 = t.Sum(p => p.TotalUserActions),
  Column2 = t.Sum(p => p.AllTotalPoints),
}

但是你必须在结果查询中包含这样的字段,现在不行。

我认为您应该在SQL中编写查询并逐步将其传输到LINQ。现在它非常令人困惑并且产生错误。


<强>更新
由于您的代码不包含此类文件,因此您收到了错误消息。哪些内容应包含字段TotalUserActionsAllTotalPoints?尝试对所有Points字段求和,但无法说出TotalUserActions的内容:

from t in (
)
select new {
  Column1 = t.Sum(p => p.TotalUserActions),
  Column2 = t.Sum(p => p.Points),
}