开发者

EF pulling out reference primary keys in a 1-M relationship

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 with开发者_Go百科out doing another query?

Cheers Anthony


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜