NotMapped Attribute in Entity Framework Core

NotMapped Attribute in Entity Framework Core (EF Core)

In this article, I will discuss NotMapped Data Annotation Attribute in Entity Framework Core (EF Core) with Examples. Please read our previous article, discussing InverseProperty Attribute in Entity Framework Core with Examples.

NotMapped Attribute in Entity Framework Core:

The NotMapped Attribute in Entity Framework Core can be applied to one or more properties of an entity class for which we do not want to create corresponding columns in the database table. By default, EF Core creates a column for each property (property having the get and set accessors) in an entity class.

Using NotMapped Attribute, we can also exclude a class from database mapping, i.e., if we apply this attribute on an Entity, for this Entity, no database table is going to be created in the database. So, the [NotMapped] Attribute overrides the default convention that EF Core follows.

Examples to Understand NotMapped Attribute in EF Core:

Before using the NotMapped Attribute in Entity Framework Core, let us first see the signature of this Attribute class. If you go to the definition of NotMappedAttribute class, you will see the following. The NotMapped Attribute denotes that property or class should be excluded from database mapping. As you can see, this class has one parameterless constructor.

NotMapped Attribute in EF Core

Let us understand the NotMapped Attribute with an Example.

Create a class file named StudentOnline.cs class and copy and paste the following code. As you can see, we created the class with a set of properties here. Then, we applied NotMapped Attribute with RegistrationNumber Property, which should exclude the corresponding column while creating the StudentOnline database table.

using System.ComponentModel.DataAnnotations.Schema;
namespace EFCoreCodeFirstDemo.Entities
{
    public class StudentOnline
    {
        public int StudentOnlineId { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }

        //Applying NotMapped Attribute in Properties
        //For the following Property, no database column will be created 
        [NotMapped]
        public int RegistrationNumber { get; set; }
    }
}

Note: If you have a property in your entity that you do not want to be represented as a column in the database, you can decorate it with the NotMapped attribute.

Please create another class file named StudentOffline.cs class and copy and paste the following code. As you can see, we also created the class with the same set of properties here. Then, we applied the NotMapped attribute on the StudentOffline Entity class, which should exclude the corresponding database table to be created in the database.

using System.ComponentModel.DataAnnotations.Schema;
namespace EFCoreCodeFirstDemo.Entities
{
    //Applying NotMapped Attribute in Entity Class
    //For the following Entity, no database table will be created 
    [NotMapped]
    public class StudentOffline
    {
        public int StudentOfflineId { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public int RegistrationNumber { get; set; }
    }
}

Note: If you have a class that you use in your DbContext but don’t want a corresponding table in the database, you can decorate the whole class with the NotMapped attribute.

Next, modify the context class as follows. As you can see, we have registered the two model classes within the context class using DbSet properties.

using Microsoft.EntityFrameworkCore;
namespace EFCoreCodeFirstDemo.Entities
{
    public class EFCoreDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }

        public DbSet<StudentOnline> OnlineStudents { get; set; }
        public DbSet<StudentOffline> OfflineStudents { get; set; }
    }
}

Note: Before proceeding further, I am deleting the Migration Folder from our project and the database.

With the changes in place, open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving DBMigration1. The name that you are giving it should not be given earlier.

NotMapped Data Annotation Attribute in EF Core with Examples

Now, if you verify the database, you will only see the StudentOnlines table, and you can also verify that there is no column mapping for the RegistrationNumber property, as shown in the image below.

NotMapped Data Annotation Attribute in EF Core with Examples

Note: Even though we have specified the StudentOffline entity in the context class, the corresponding database table is not generated. This is because we have applied the StudentOffline entity with the NotMapped Attribute.

The Entity Framework Core will not create a column in the database table for a property if it does not have both getters or setters. To better understand, please modify the StudentOnline.cs class as follows. As you can see, for the Property RegistrationNumber, we only GET Accessor, not the SET Accessor. And for the Property RollNumber, we have only the SET Accessor, not the GET Accessor. So, in this case, for RollNumber and RegistrationNumber Properties, the corresponding database columns will not be created in the database.

namespace EFCoreCodeFirstDemo.Entities
{
    public class StudentOnline
    {
        private int _RollNumber;

        //Properties Having both get and set Accessor
        public int StudentOnlineId { get; set; }
        public string? FirstName { get; set; }
        public string? LastName { get; set; }

        //Property Having only get Accessor
        public int RegistrationNumber { get { return StudentOnlineId; } }

        //Property Having only set Accessor
        public int RollNumber { set { _RollNumber = value; } }
    }
}

With the changes in place, open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving DBMigration2. The name that you are giving it should not be given earlier.

NotMapped Data Annotation Attribute in Entity Framework Core with Examples

If you verify the database, you will see no column mapping for the RegistrationNumber and RollNumber properties, as shown in the image below.

NotMapped Data Annotation Attribute in Entity Framework Core with Examples

Advantages and Disadvantages of NotMapped Attribute in EF Core:
Advantages of NotMapped Attribute in EF Core:
  • Flexibility: Allows you to have properties in your entities that exist only in your application logic and aren’t persisted in the database.
  • Performance: Excluding unnecessary columns can simplify the database schema and optimize the performance of CRUD operations by not dealing with fields that don’t need to be stored or retrieved.
  • Application Logic vs. Data Logic: Not all properties in an entity need to be persisted in the database. Some properties might exist purely for the application’s logic. The NotMapped attribute allows developers to distinguish between application-specific logic and data that should be persisted.
  • Avoid Redundancy: If you have properties that can be derived or computed from other properties, marking them as NotMapped prevents redundant storage. This is common with calculated properties.
Disadvantages of NotMapped Attribute in EF Core:
  • Confusion: If not clearly documented or understood, other developers might be unaware that a certain property isn’t persisted in the database. They might assume that all properties of an entity are saved, which could lead to data loss or other unexpected behaviors.
  • Maintenance: If the requirements change and a previously non-persistent property now needs to be stored in the database, developers need to remove the NotMapped attribute, ensure that migrations are correctly applied, and handle potential data initialization or transfers.
  • Consistency: In a large codebase, if some developers use the NotMapped attribute while others use the Fluent API configuration to achieve the same goal, it might lead to inconsistencies in how entities are defined.
  • Possible Overuse: Developers might misuse the NotMapped attribute to exclude properties they’re unsure about rather than making definitive modeling decisions, leading to a domain model that’s not well-defined or thought out.

When using Entity Framework Core (EF Core), the NotMapped attribute specifies that a particular property or class should not be mapped to a table or column in the database. EF Core usually maps all entity properties to database columns, but in some cases, certain properties should not be persisted in the database. In these situations, the NotMapped attribute is used to exclude those properties from being persisted in the database.

In the next article, I will discuss the Required Attribute in Entity Framework Core with Examples. In this article, I try to explain the NotMapped Data Annotation Attribute in Entity Framework Core with Examples. I hope you enjoyed this NotMapped Attribute in EF Core with Examples article.

Leave a Reply

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