what's the catch (select new in LINQ vs simply filling the object)
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!
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.
精彩评论