0

I have a DB that looks like this:

 Houses
    - HouseId
 Rooms
    - RoomId

 HouseRooms
    - HouseRoomId
    - HouseId
    - RoomId

class House
{
   [Key]
   public virtual int HouseId{ get; set; }


   public DbSet<HouseRoom> Rooms{ get; set; }
 }    

class HouseRoom

{ [Key] public virtual int HouseRoomId{ get; set; }

   public virtual int HouseId{ get; set; }
   public virtual int RoomId{ get; set; }

   [ForeignKey("RoomId")]
   Public Role RoomInfo {get; set;}
}

class Room
{ 
   [Key] 
   public virtual int RoomId {get; set;}

   public string RoomName {get; set;}
} 

I just need the House entity/mode to load all the rooms records. Noticed that the JOIN table has a PK name HouseRoomId but this is not the key that need to match the key in House. House.HouseId need to match HouseRoom.HouseId.

How can I get this to work?

3
  • Just out of curiosity, why/how can a Room be in more than 1 House? Commented Jun 4, 2013 at 0:41
  • it is a RoomType really like Kitchen, BED 1 etc for example,, each house has a floorplan and each floor plan has similar roomtypes. The example is just to get an idea how to get one to many working in code first. Commented Jun 4, 2013 at 0:43
  • Ah, so it's more of a Room template, rather than a room itself, I understand :) Commented Jun 4, 2013 at 0:58

1 Answer 1

2

Ok first this is a many-to-many, not one-to-many. Second, you need to set the relationship on ModelCreation to let the DbContext know about this relationship. Also, you need to make your List<Room> virtual to enable it to load when you need it. Please look at this example. Code First Entity Framework Many-to-Many relationships

Also, for the record, you do not need to specify [key], it is already there for you by default

Sign up to request clarification or add additional context in comments.

1 Comment

The virual did it. I know it was a many to many but I wasnt able to get the one to many loaded. I think I have it now. Thanks. Still dont know how it knows how to map the relationships..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.