简体   繁体   中英

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

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 });

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
             };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM