gpt4 book ai didi

c# - Linq 匿名类型成员必须在子查询中声明

转载 作者:行者123 更新时间:2023-11-30 12:44:31 25 4
gpt4 key购买 nike

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

Linq 中的预期输出:

TotalPoints Name

231 John

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

Invalid expression term '.'

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

到目前为止的 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 的帮助会很棒。

最佳答案

您的查询结构是:

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),
}

关于c# - Linq 匿名类型成员必须在子查询中声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com