Why do we need the backing fields in EF Core?

1.2k Views Asked by At

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.

2

There are 2 best solutions below

3
On BEST ANSWER

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>
0
On

I feel like your question was referring to manually configured backing fields so I will provide some common reasons why someone would want to manually configure a backing field.

  1. If you want a backing field that does not use any of the possible conventions that allow it to be recognised by EF as the backing field for its property.

In one of the example provided in the EF Core docs for Backing Fields, the property name is Url but the backing field name is _validatedUrl. Manual configuration of the backing field is needed in this scenario for EF to correctly handle the property.

  1. If you want to set the property access mode. EF core allows you to configure the property access mode it uses to access properties. This is useful if you want to change the data being written to the database or being retrieve from the database within your code but keep it separate from what is held within the database.

  2. If you want to save the contents of a field to the database without having a C# property (see EF Core Docs for "field-only properties").

These are all very specific scenarios - it's perfectly reasonable to never manually configure a backing property in EF.