What constitutes explicit creation of entities in LINQ to SQL? What elegant "solutions" are there to
Posted
by Marcelo Zabani
on Stack Overflow
See other posts from Stack Overflow
or by Marcelo Zabani
Published on 2010-03-14T21:41:57Z
Indexed on
2010/03/14
21:45 UTC
Read the original article
Hit count: 145
linq-to-sql
Hi SO, I've been having problems with the rather famous "Explicit construction of entity type '##' in query is not allowed." error.
Now, for what I understand, this exists because if explicit construction of these objects were allowed, tracking changes to the database would be very complicated.
So I ask: What constitutes the explicit creation of these objects? In other terms:
Why can I do this:
Product foo = new Product();
foo.productName = "Something";
But can't do this:
var bar = (from item in myDataContext.Products
select new Product {
productName = item.productName
}).ToList();
I think that when running the LINQ query, some kind of association is made between the objects selected and the table rows retrieved (and this is why newing a Product in the first snippet of code is no problem at all, because no associations were made). I, however, would like to understand this a little more in depth (and this is my first question to you, that is: what is the difference from one snippet of code to another).
Now, I've heard of a few ways to attack this problem:
1) The creation of a class that inherits the linq class (or one that has the same properties)
2) Selecting anonymous objects
And this leads me to my second question:
If you chose one of the the two approaches above, which one did you choose and why? What other problems did your approach introduce? Are there any other approaches?
© Stack Overflow or respective owner