Tuesday, 17 September 2013

Access Id of parent entity without actually loading it in EntityFramework code first

Access Id of parent entity without actually loading it in EntityFramework
code first

I have two entities:
public class Parent
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class Child
{
public Guid Id { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
}
I can query Child entity with or without parent by using Include.
public void Test()
{
var child = context.Set<Child>().Include(x => x.Parent)
.FirstOrDefault(x => x.Id == Guid.Parse("<some_id>"));
}
But in some cases I have all Parent entities already cached in memory, And
i want to skip join and query Child entity with only Id propery loaded.
And then get actual Parent from cache by Id:
public void Test()
{
var cachedParents = new List<Parent>();
var child = context.Set<Child>()
.FirstOrDefault(x => x.Id == Guid.Parse("<some_id>"));
var parent = cachedParents.FirstOrDefault(x => x.Id == child.Parent.Id);
}
But child gets loaded with child.Parent == null.
Is there some way to have child.Parent to be loaded or just access
child.Parent.Id (ParentId column) property?

No comments:

Post a Comment