Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop error

Tags:

c#

I'm gettin an error pointing to in in the foreach loop!? Has never happens before. What could be the reason for this? Have I missed something?

Error message:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code


Additional information: Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

My code:

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);
}
like image 837
3D-kreativ Avatar asked May 12 '16 09:05

3D-kreativ


2 Answers

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

should be:

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

If ProjectID is int?,

var w = from x in db.Activities where 
        x.ProjectID.HasValue &&
        x.ProjectID.Value == 1 select x;
like image 135
Mike Debela Avatar answered Sep 30 '22 20:09

Mike Debela


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

Since the ProjectID is an int? you have to check for nullity and then cast it.

like image 44
Felix Castor Avatar answered Sep 30 '22 18:09

Felix Castor