Foreach循环错误

时间:2016-05-12 09:39:57

标签: c#

我在foreach循环中指向in时出错!?从来没有发生过。这可能是什么原因?我错过了什么吗?

错误讯息:

  

类型' System.NotSupportedException'的例外情况       发生在EntityFramework.SqlServer.dll中但未在用户代码中处理

  

其他信息:无法创建常量        类型的值' System.Object'。只有原始类型        或者在此上下文中支持枚举类型。

我的代码:

List<int> WeeksInProject = new List<int>();
var w = from x in db.Activities 
        where x.ProjectID.Equals(1) 
        select x;

foreach (var wNum in w)
{
    WeeksInProject.Add(wNum.WeekNumber);
}

2 个答案:

答案 0 :(得分:6)

<button class='addNew'>
        <i class="fa fa-plus" ></i> Add new 
        <span style='text-decoration:underline'>Object</span>
</button>

应该是:

var w = from x in db.Activities 
        where x.ProjectID.Equals(1) select x;

如果var w = from x in db.Activities where x.ProjectID == 1 select x; ProjectID

int?

答案 1 :(得分:2)

List<int> WeeksInProject = new List<int>();
var w = from x in db.Activities 
        where x.ProjectID != null && (int)x.ProjectID == 1 
        select x;

foreach (var wNum in w)
{
    WeeksInProject.Add(wNum.WeekNumber);
}

由于ProjectID是int?,您必须检查无效然后投射它。

相关问题