There are times when you don’t want to map a property in a class to the table column in Entity Framework Code First.
Let us consider the following Customer Model class
In this Customer model class, we have a property by Name “FullName” .
We would use this property to display the complete name of the customer in our application. We want only the FirstName and LastName properties to be stored as database table columns and we don’t want to store FullName property in database as its being used only for display purpose in application.
As other configurations in Entity Framework, there are 2 ways to ignore class property
- Data Annotation
- Fluent API
You have to use [NotMapped] Data Attribute on the property which you don’t want to map to the database table column. Below is the updated Customer Model with its DataContext class
Some prefer Model classes to be very clean – without any Data Annotations. They prefer the configuration to be done DataContext class.
You can use the Ignore method on the class property to prevent it from mapping to the database column.
Below is the same Customer example using Fluent API
Irrespective of whether the configuration is done through Data Annotation or Fluent API, usage of the DBContext would be same. Below is the usage.
When you run the application and see the database table structure of Customers, it would not have FullName property
The complete code is available at https://github.com/mugil-dotnet/IgnorePropertyInEF
If you like this article, please subscribe. I’ll send you useful articles along the way.[x_subscribe form=”277″]