By Code-First convention, Entity Framework creates a column for every public property that is of a supported data type and has both a getter and a setter. [NotMapped] annotation must be applied to any properties that we do NOT want a column in a database table for.
An example of a property that we might not want to store in the database is a student’s full name based on their first and last name. That can be calculated on the fly and there is no need to store it in the database.
public string FullName => string.Format("{0} {1}", FirstName, LastName);
The "FullName" property has only a getter and no setter, so by default, Entity Framework will NOT create a column for it.
Another example of a property that we might not want to store in the database is a student’s "AverageGrade". We do not want to get the AverageGrade on-demand; instead we might have a routine elsewhere that calculates it.
[NotMapped]
public float AverageGrade { set; get; }
The "AverageGrade" must be marked [NotMapped] annotation, else Entity Framework will create a column for it.
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; }
}
For the above Entity we will see inside DbMigration.cs
CreateTable(
"dbo.Students",
c => new
{
Id = c.Int(nullable: false, identity: true),
FirstName = c.String(),
LastName = c.String(),
})
.PrimaryKey(t => t.Id);
and in SQL Server Management Studio