Entity Framework - When using table joins

When you are working with join tables there are a few things that have to be done in order to get a handle on the necessary properties.

First, when you have a join table with no payload(meaning that only two columns show up in the model, ex: UserID and GroupID) these entities will not show up in the edmx. In our example the user table will show a navigation property to the Group entity, and the Group entity will show a navigation property to the User entity

Even though those navigation properties show up and you feel that you will have a handle on them you will not.

You will be unable to do this

User _user = new User();

_User.Groups.....

If you have other entities that do not work off of join tables then you will be able to do this

User _user = new User();

_user.Program

Because there is a join table there is some additional work that has to be done in order to get a handle on this navigation property.

Step 1: In the domain context class you have to change your calling method to "include" the entity that you are looking to get a handle on.

 public IQueryable<User> GetUsersByProgramID(int programID)
        {
            return _userRepository.All().Where(x => x.ProgramID == programID).Include("Groups");
        }

at the end of this method we are using the .Include("Groups") on the GetUserByProgramID

Step 2: in the domain context metadata you have to set some attributes on the groups property.

            [Include]
            [Association("Groups""UserID""GroupID")]
            public EntityCollection<Group> Groups
            {
                get;
                set;
            }

this is the internal sealed class UserMetadata -

we have to set up the association - within that is the name of the entity and the two columns in the join table.

 

another note - anytime that you are using an include  you should go into the metadata class and set that property to [Include] - you dont have to set the [Association] unless you are using a join table.

Twitter