views:

12

answers:

1

Hi guys

In a 1-M relationship, in the many side of the relationship I can pull out the Id of the parent item without doing another query using something like the following:

this.ParentReference.EntityKey.EntityKeyValues[0].Value

But what I am wondering if there a similar way of pulling out the many ID's from the 1 without doing another query?

Cheers Anthony

+1  A: 

No, not unless you eager-load (or project) the relationship.

When you load this, by itself, the EF loads all the data from the table which contains this. It doesn't JOIN in any other tables.

When you load Parent, the data containing the child IDs is in another DB table. So unless you tell the EF to load it, it will not JOIN in that other table.

So if you know that you will be needing the "child" IDs when loading Parent, you can eager load:

var p = Context.Parents.Include("Children").Where(p => p.Id == id).First();

...or project:

var q = from p in Context.Parents
        where p.Id == id
        select new
        {
            Parent = p,
            ChildIds = from c in p.Children
                       select c.Id
        };
Craig Stuntz