Search code examples
propertiesentity-framework-corefieldentitiesbacking-field

Why do we need the backing fields in EF Core?


Why do we need the backing fields in EF Core?

Why would someone want to use a field instead of a property while working with the entities? I can not come up with such a case. That probably means that I do not understand or I am missing something about the fields, since I thought that I could accomplish anything what is possible to do with the fields with the properties as well.

I am learning the EF Core through the tutorials over here.


Solution

  • Properties do not store anything. They are a pair of set and get methods. You must have a backing field to have them store something.

    public class Data
    {
        private int _id; // Backing field used by property to store the value.
    
        // Property whose name is used by EF Core to map to a column name.
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
    
        ... more properties
    }
    

    But you can simplify this code by using automatic properties

    public class Data
    {
        // Auto-implemented property. Backing field and implementation are hidden.
        public int Id { get; set; }
    
        ... more properties
    }
    

    This 2nd code snippet does exactly the same as the first one.


    EF Core prefers backing fields over properties if their name can be inferred from the property name. The Conventions say:

    By convention, the following fields will be discovered as backing fields for a given property (listed in precedence order). Fields are only discovered for properties that are included in the model. For more information on which properties are included in the model, see Including & Excluding Properties.

    • _<camel-cased property name>
    • _<property name>
    • m_<camel-cased property name>
    • m_<property name>