views:

99

answers:

1

Hello everybody, can someone please explain the difference between these 2 pieces of code:

var temp = (from c in Context.SomeTable 
            select new SomeObject { name=c.Name, created = c.Created}).ToList();

and this :

var temp = (from c in Context.SomeTable select c);
foreach(SomeTable t in temp)
{
SomeObject so = new SomeObject();
so.name = t.Name;
so.created = t.Created;
}

SomeTable.Created is a nullable datetime type field in the database.

While the first piece throws an exception:

Sqldatetime overflow. must be between 1/1/1753 12:00:00 am and 12/31/9999 11:59:59 pm.

the second one works.

Thank You!

+1  A: 

In the first code no c will be read from SomeTable or instance of SomeObject will be created until something enumerates temp.

The second this enumeration takes place.

Therefore I would expect there is an issue with the validity of Context.SomeTable when temp is enumerated in the first case.

Test this by changing the first block to:

var temp = (from c in Context.SomeTable 
            select new SomeObject { name=c.Name, created = c.Created}
           ).ToList();

which forces immediate enumeration.

Richard
Since he gets an exception from the first piece of code, I'd say it is safe to assume he's actually executing the query.
Lasse V. Karlsen
yep, srry. forgot to add .ToList() in my post.i had it too originally.
vbobruisk
So did you get an answer to your question or not? It sounds to me as you already did what this answer said you should do, but still have the problem, yet you've marked it as the accepted answer.
Lasse V. Karlsen
@Lasse: "safe to assume [...]": See my third paragraph, between creating the IQueryable<T> and enumerating it something changed.
Richard