0

I have module which is not mapped to database and is use to generate report.

public class Report
{
    public int USERID { get; set; }
    public DateTime DateToCal { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
    public TimeSpan? Intime { get; set; }
    public TimeSpan?  OutTime { get; set; }
}

I generate a query and fill some properties(USERID, DateToCal, Name, Position, Intime) of report and remaining properties OutTime is null.

var query = .....;

Now what I want is foreach item of query( of type Report) set value for OutTime as

foreach(var items in query)
            {
                var outtime= from x in con.CHECKINOUTs
                              where x.USERID == items.USERID && EntityFunctions.TruncateTime(x.CHECKTIME) == EntityFunctions.TruncateTime(items.DateToCal && x.CHECKTYPE == "O"
                              select x.CHECKTIME
                              .Single();
                items.OutTime= outtime.TimeOfDay;
            }

Now problem is, on mousehover to items.OutTime with in foreach there appear value but if I out from foreach and mousehover to query there is still OutTime is null. There not appear value what I set. Is this is possible to set value of entities such way. Or what is my problem?

Thank you.

link2jagann
  • 183
  • 1
  • 5
  • 12

3 Answers3

0

The problem is that "items" is only available within the foreach loop and is discarded at the end of each iteration. If you want to persist the value, you could use a for loop instead and directly set the item in the enumerable "query":

for(int index = 0; index < query.Length; ++index;)
            {
                var outtime= from x in con.CHECKINOUTs
                              where x.USERID == items.USERID &&         
                              EntityFunctions.TruncateTime(x.CHECKTIME) == 
                              EntityFunctions.TruncateTime(items.DateToCal && x.CHECKTYPE == "O"
                              select x.CHECKTIME
                              .Single();
                query[index].OutTime= outtime.TimeOfDay;
            }
user489998
  • 4,473
  • 2
  • 29
  • 35
0

Try first to execute your linq query with method First():

foreach(var items in query)
            {

                var outtime= (from x in con.CHECKINOUTs
                              where x.USERID == items.USERID && 
                              EntityFunctions.TruncateTime(x.CHECKTIME) 
                               == EntityFunctions.TruncateTime(items.DateToCal && x.CHECKTYPE == "O"
                               select x.CHECKTIME).First();

                items.OutTime = outtime.TimeOfDay;
            }
Andrey Gubal
  • 3,481
  • 2
  • 18
  • 21
0

Please see this topic That is because foreach is meant to iterate over a container, making sure each item is visited exactly one, without changing the container, to avoid nasty side effects.

Community
  • 1
  • 1
Ivan
  • 1