【问题标题】:Unable to create a constant value of type 'xxx'. Only primitive types or enumeration types are supported in this context无法创建类型为“xxx”的常量值。此上下文仅支持原始类型或枚举类型
【发布时间】:2015-08-26 16:33:04
【问题描述】:

我有两个表,分别是 state 和 namelist。

状态

------------
id | state
------------
1  |xxx
2  |yyy

名单

---------------
id|Name   |stateid
--------------
1|aaa     |1
2|abb     |1
3|ccc     |2
4|dds     |2

我希望结果表为

------------------
state   |count
-------------------
xxx     | 2
yyy     | 2

我想要使用 linq 查询的上述结果

我尝试了以下代码,但返回错误为(无法创建类型为“xxx”的常量值。此上下文中仅支持原始类型或枚举类型。)

var count= (from n in bc.db.state 
            select new 
                  { 
                    states = n.state, 
                    count = (from c in bc.db.namelist 
                             where c.stateid == n.id 
                             select n).Count() 
                   });

有人知道如何解决这个问题吗?

【问题讨论】:

标签: c# linq


【解决方案1】:

您需要使用 group by...

var list= 
(from n in bc.db.state 
join c in bc.db.namelist on n.id equals c.stateid 
group n by n.state into g
select new 
{
    State = g.Key,
    Count = g.Count()
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2020-10-08
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多