NotMapped 屬性

通過 Code-First 約定,實體框架為每個公共屬性建立一個列,該列具有受支援的資料型別並且同時具有 getter 和 setter。 [NotMapped] 註釋必須應用於我們希望資料庫表中的列的任何屬性。

我們可能不希望儲存在資料庫中的屬性的示例是學生的姓氏,基於他們的名字和姓氏。這可以在執行中計算,不需要將其儲存在資料庫中。

public string FullName => string.Format("{0} {1}", FirstName, LastName);

全名屬性只有一個 getter 和沒有 setter,因此預設情況下,實體框架將為它建立一個列。

我們可能不想儲存在資料庫中的另一個屬性示例是學生的 AverageGrade。我們不希望按需獲得 AverageGrade; 相反,我們可能在別處計算它。

[NotMapped]
public float AverageGrade { set; get; }

AverageGrade 必須標記為 [NotMapped] 註釋,否則 Entity Framework 將為其建立一個列。

using System.ComponentModel.DataAnnotations.Schema;

public class Student
{
    public int Id { set; get; }

    public string FirstName { set; get; }

    public string LastName { set; get; }

    public string FullName => string.Format("{0} {1}", FirstName, LastName);

    [NotMapped]
    public float AverageGrade { set; get; }
}

對於上面的實體,我們將在 DbMigration.cs 中看到

CreateTable(
    "dbo.Students",
     c => new
         {
             Id = c.Int(nullable: false, identity: true),
             FirstName = c.String(),
             LastName = c.String(),
         })
     .PrimaryKey(t => t.Id);

並在 SQL Server Management Studio 中

StackOverflow 文件