tags:

views:

363

answers:

3

Hi,

my code is:

            List<Benutzer> users = (from a in dc.Benutzer
                                    select a).ToList();

I need this code but I only want to select 3 of the 20 Columns in the "Benutzer"-Table. What is the syntax for that?

+3  A: 
    List<Benutzer> users = (from a in dc.Benutzer
                            select new Benutzer{
                             myCol= a.myCol,
                             myCol2 = a.myCol2
                             }).ToList();

I think that's what you want if you want to make the same kind of list. But that assumes that the properties you are setting have public setters.

qui
I get an error, that I can't use "Benutzer" in there.
Kovu
You need a comma to seperate the fields, although i doubt that's why it's breaking
qui
I just tried it on my machine with a very similar use case and it worked. Can you paste the exact error?
qui
Explicit construction of entity type 'DAL.Benutzer' in query is not allowed.Thats the error
Kovu
Try removing the `Benutzer` from the query then: `select new { myCol = a.myCol, ... }` to construct an anonymous type.
Joey
I don't wnat anymous
Kovu
I'm guessing it's because you dont have a constructor which allows this. Make a constructor for your Benutzer class and do it the normal way. select new Benutzer(myCol, myCol2, etc..)
qui
+6  A: 

Here's a query expression:

var users = (from a in dc.Benutzer
             select new { a.Name, a.Age, a.Occupation }).ToList();

Or in dot notation:

var users = dc.Benutzer.Select(a => new { a.Name, a.Age, a.Occupation })
                       .ToList();

Note that this returns a list of an anonymous type rather than instances of Benutzer. Personally I prefer this approach over creating a list of partially populated instances, as then anyone dealing with the partial instances needs to check whether they came from to find out what will really be there.

EDIT: If you really want to build instances of Benutzer, and LINQ isn't letting you do so in a query (I'm not sure why) you could always do:

List<Benutzer> users = dc.Benutzer
    .Select(a => new { a.Name, a.Age, a.Occupation })
    .AsEnumerable() // Forces the rest of the query to execute locally
    .Select(x => new Benutzer { Name = x.Name, Age = x.Age, 
                                Occupation = x.Occupation })
    .ToList();

i.e. use the anonymous type just as a DTO. Note that the returned Benutzer objects won't be associated with a context though.

Jon Skeet
How I can typisite it?
Kovu
What do you mean by "typisite"?
Jon Skeet
I want the type to be Benutzer, not anonymous.
Kovu
You can if you provide Benutzer have parameterless constructor and public setters for desired properties. Or and constructor that fits the same purpose.
Petar Repac
A: 

try:

var list = (from a in dc.Benutzer select new {a.Col1, a.Col2, a.Col3}).ToList();

but now you have list of anonymous object not of Benutzer objects.

TheVillageIdiot