Data Annotations NotMapped Attribute in EF Core

Apply the NotMapped attribute on those properties, which you do not want to include in your database table. This attribute usually used in the case of calculated fields like Age, Amount, etc. This attribute is similar to the Fluent API Ignore method in EF Core.

NotMapped Attribute

Entity Framework conventions or Entity Framework Core Conventions creates the table column for every public property which has getters & setters. This behavior can be overridden using the NotMapped attribute

This attribute is from the System.ComponentModel.DataAnnotations.Schema Namespace

In the following example, we have included age property. We can calculate the age property from the DOB Property. Hence no need to create the database column for the age property

The above model maps to the database as shown below. Tne EF will not create the Age column in the database, because of the NotMapped attribute on the property. Without this attribute, the entity framework will create the column in the database

Data Annotation NotMapped Attribute in Entity Framework Code First
Data Annotation NotMapped Attribute in Entity Framework Code First

NotMapped Attribute on tables

You can also apply the NotMapped attribute on the class itself. This will exlcude the model from the database

Reference

  1. NotMappedAttribute Class
  2. Ignore method

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top