Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Jekas Avatar asked Jul 01 '26 15:07

Jekas


1 Answers

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);
like image 68
Slauma Avatar answered Jul 03 '26 03:07

Slauma