0

Every building has multiple rooms. I would like to return data from a building that includes a room number from every room owned by said building via a class buildingView, which looks like this right now (with some pseudocode):

public class buildingView
{
    public int id { get; set; }
    public string name { get; set; }
    ...
    public *something* roomNumbers *something*
}

To that end, I have the following query:

buildingView building = db.buildings.Select(b => new buildingView
{
    id = b.id,
    name = b.name,
    ...
    roomNumbers = *I have no idea*
})
.Where(b => b.id == id)
.SingleOrDefault();

Room numbers are all strings, if that's relevant.

My questions:

How can I get my list of room numbers?

How can I improve my question's title? I lack the vocabulary right now to do better.

Is there a another way entirely?

Thanks!

P.S. If you are going to downvote, please say why. Otherwise how will I know how to improve my questions?

crowhill
  • 2,398
  • 3
  • 26
  • 55
  • 1
    Have a look at the accepted answer for [Entity Framework: Querying Child Entities](http://stackoverflow.com/questions/7753039/entity-framework-querying-child-entities). Whereas they're looking based on age, you'd use whatever criteria you've defined to match the room to build (e.g. BuildingId). If you need more help please add your `building` and `room` classes to the question. – Tone Jul 05 '16 at 19:51
  • OP: How would you do it without Entity Framework? Write it that way and let EF figure out the rest. It's what EF is for. – Spivonious Jul 05 '16 at 19:59

1 Answers1

1

Assuming you have a class like ...

class Building
{
    ...
    public ICollection<Room> Rooms { get; set; }
}

And that BuildingView is ...

public class BuildingView
{
    public int Id { get; set; }
    public string Name { get; set; }
    ...
    public IEnumerable<string> RoomNumbers { get; set; }
}

... you can get the concatenated room numbers as follows:

var buildingViews = context.Buildings
                           .Select(b => new BuildingView
                            {
                                Id = b.Id,
                                Nems = b.Name,
                                RoomNumbers = b.Rooms
                                               .Select(r => r.Number)
                            });

Side note: it's really recommended to use C# naming conventions, like PascalCase for class and property names.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291