efcore icon indicating copy to clipboard operation
efcore copied to clipboard

NotMapped composed property causes all properties load in select statement in EF Core

Open MohammadAkbari opened this issue 5 years ago • 1 comments

I use EF Core 5 in a project, one of my entities contains a NotMapped property that mixed two properties of the entity, I expect in the select statement only properties that contain in the select statement load from the database but after profiling, I have seen that all properties were loaded.

As a sample, the Contact entity contains one NotMapped property as follows.

public class Contact
{
	public int ContactId { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	[NotMapped]
	public string FullName => $"{FirstName} {LastName}";
	public string Email { get; set; } 
	public string Phone { get; set; } 
	public string Address { get; set; } 
}

public class SampleContext : DbContext
{
	public DbSet<Contact> Contacts { get; set; }
}

In the following query, I need only ContactId and FullName, I expect only ContactId, FirstName, LastName to load in the TSQL query, but all properties are loaded.

var list = dbContext.Contacts.Select( e => new
	{
		e.ContactId,
		e.FullName
	}).ToList();

MohammadAkbari avatar Aug 27 '21 07:08 MohammadAkbari

@MohammadAkbari your FullName property is completely opaque to EF Core - EF has no way of knowing that the property accesses FirstName and LastName; as a result, the entire entity loaded.

You may want to take a look at computed columns, where FullName would be computed in the database (rather than in .NET) and retrieved just like any other column. Another solution would be to first project out to your own Contact instance which only contains the necessary properties, and extract FullName from that:

var list = ctx.Contacts
    .Select(e => new
    {
        e.ContactId,
        new Contact
        {
            FirstName = e.FirstName,
            LastName = e.LastName
        }.FullName
    })
    .ToList();

roji avatar Aug 27 '21 11:08 roji