Skip to content Skip to sidebar Skip to footer

Ef Core Fix-up When Querying Subset Of Columns

From the documentation: Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even

Solution 1:

When you project into a new type yourself in the query, EF Core does not track the object coming out of the query even if they are of type an entity which is part of Model. This is by design.

Since in your case Pages are not getting tracked, Events have nothing to do fixup with. Hence you are seeing null navigation properties.

This behavior was same in previous version (EF6). The main reason for not tracking is, as in your case, you are creating new Page without loading Content. If we track the new entity then it will have Content set to null (default(string)). If you mark this whole entity as modified then SaveChanges will end up saving null value in Content column in database. This would cause data loss. Due to minor error could cause major issue like data loss, EF Core does not track entities by default. Another reason is weak entity types (or complex types in EF6) which share CLR type with other entities but uniquely identified through Parent type, if you project out such entity then EF Core cannot figure out which entity type it is without parent information.

You could put those entities in changetracker by calling Attach method, which will cause fix up and you will get desired behavior. Be careful not to save them.

In general the scenario you want is useful. This issue is tracking support for that in EF Core.

Solution 2:

I don't think that should work. Did you verify this behavior worked in previous versions of EntityFramework? Since, you aren't pulling out the full entity, and only properties of it, and then passing it into a new Entity, you are essentially just Selecting properties and creating a new Entity.

If you would like this to attach you can manually call the Attach Method after selecting your page

var pages = _dbContext.Page.Select(page =>newPage
    {
        Id = page.Id,
        Title = page.Title
    }).ToList();

pages.ForEach(p => _dbContext.Page.Attach(p));

Keep in mind that if you call SaveChanges After this you will lose the unloaded properties, so only use this when calling Get Methods

Post a Comment for "Ef Core Fix-up When Querying Subset Of Columns"