为什么我们需要EF Core中的后备字段?

问题描述 投票:0回答:1

为什么我们需要EF Core中的后备字段?

为什么有人在使用实体时为什么要使用字段而不是属性?我无法提出这种情况。这可能意味着我不了解或缺少有关字段的信息,因为我认为我也可以利用属性来完成与字段有关的所有工作。

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

properties entity-framework-core field entities backing-field
1个回答
2
投票

属性不存储任何内容。它们是一对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说:

按照惯例,以下字段将作为给定属性(按优先顺序列出)的后备字段被发现。仅针对模型中包含的属性发现字段。有关模型中包含哪些属性的更多信息,请参见Including & Excluding Properties

  • _
  • _
  • m_
  • m_
© www.soinside.com 2019 - 2024. All rights reserved.