jonas vermeulen
jonas vermeulen

Reputation: 1245

select properties of entity ef linq

i have query for a list of objects (ex Rooms) that contains an object (ex Door) Door has many properties (ex width, height, color), but i only need color.

now i have

Rooms.include(r => r.Door) 

but this takes all properties of door. if i do

Rooms.include(r => r.Door.color) 

than it says that color is not a navigational property of door.

How can i only select color ?

i hope i made myself clear. any help is appreciated

Upvotes: 1

Views: 1932

Answers (2)

Jace Rhea
Jace Rhea

Reputation: 5018

Include is not used for selecting, it is used to tell the compiler that the property should be included in the query. Just use a select to get the color and include Rooms in the select.

Edit: Answer was edited after additional information was provided.

Rooms.Select(r => new { Color = r.Door.color, Room = r });

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Unfortunately you cannot conditionally load properties of related entity - you either load whole door entity, or don't include that entity. But you can use anonymous type to return room and color of it's door:

 var rooms = from r in db.Rooms
             select new {
                 Room = r,
                 DoorColor = r.Door.Color
             };

Upvotes: 1

Related Questions