为什么我们需要 EF Core 中的支持字段?

Why do we need the backing fields in EF Core?

为什么我们需要 EF Core 中的支持字段?

为什么有人在处理实体时想要使用字段而不是 属性?我想不出这样的例子。这可能意味着我不理解或遗漏了有关字段的某些信息,因为我认为我也可以完成任何可能对具有属性的字段所做的事情。

我正在通过 here 的教程学习 EF Core。

属性不存储任何内容。它们是一对 set 和 get 方法。你必须有一个支持字段才能让它们存储一些东西。

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
}

但是您可以使用自动属性简化此代码

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

    ... more properties
}

第二个代码片段与第一个代码片段完全相同。


如果可以从 属性 名称推断出它们的名称,EF Core 更喜欢支持字段而不是属性。 Conventions 说:

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>