I’m trying to use LINQ to SQL to select a few specific columns from a table and return the result as a strongly typed list of objects.
For Example:
var result = (from a in DataContext.Persons
where a.Age > 18
select new Person
{
Name = a.Name,
Age = a.Age
}
).ToList();
Any help would be greatly appreciated.
It builds fine, but when I run it, I get the error. Explicit construction of entity type MyEntity in query is not allowed.
Basically you are doing it the right way. However, you should use an instance of the
DataContextfor querying (it’s not obvious thatDataContextis an instance or the type name from your query):Apparently, the
Personclass is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:You can freely swap
varwithList<PersonInformation>here without affecting anything (as this is what the compiler does).Otherwise, if you are working locally with the query, I suggest considering an anonymous type:
Note that in all of these cases, the
resultis statically typed (it’s type is known at compile time). The latter type is aListof a compiler generated anonymous class similar to thePersonInformationclass I wrote above. As of C# 3.0, there’s no dynamic typing in the language.UPDATE:
If you really want to return a
List<Person>(which might or might not be the best thing to do), you can do this:You can merge the above statements too, but I separated them for clarity.