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?
You can use Select to fetch individual properties (or any selection of properties) from the database:
Guid childId = Guid.Parse("<some_id>");
var parentId = context.Set<Child>()
.Where(x => x.Id == childId)
.Select(x => x.Parent.Id)
.FirstOrDefault();
var parent = cachedParents.FirstOrDefault(x => x.Id == parentId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With