Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 301
Mohammad Akbari Avatar asked Oct 29 '25 17:10

Mohammad Akbari


1 Answers

If you just want to load some columns you could:

var list = dbContext.Contacts
    .Where(...)
    .Select( e => new
    {
        e.ContactId,
        LastName = e.FirstName + " " + e.LastName
    })
    .ToList() // hit the database 
like image 136
tymtam Avatar answered Oct 31 '25 08:10

tymtam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!