Search code examples
entity-frameworkentity-framework-6sizebytetransfer

Entity framework transferred data in bytes


I'm using EF6

this is my class

public partial class tbl_Persons
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public byte Age { get; set; }
    }

How much (bytes) will be transferred from the server to the client when used this code ?

using (var db = new testEntities())
{
    var q = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234).Age;
}

Just transferred {(Age)(1 byte)} or transferred all properties {(ID + Name + Age)(10 bytes)} then select Age on client ?

How can I transfer only (Age)(1 byte) ? (I need to transfer minimum data from server)


Solution

  • The expression

    var q = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234).Age;
    

    is equivalent of

    var person = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234);
    var age = person.Age;
    

    So you first retrieve and materialize a whole object (with all properties) from the database, and then take a single property (byte in your case) from the result.

    In order to fetch just the property in question, you should use a not so concise, but more efficient Where + Select + FirstOrDefault (no predicate version):

    var age = db.tbl_Persons.Where(p => p.ID == 1234).Select(p => p.Age).FirstOrDefault();
    

    or with query syntax

    var age = (from p in db.tbl_Persons where p.ID == 1234 select p.Age).FirstOrDefault();