Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Exclude Type from the Model in Entity Framework Code First

5.00/5 (5 votes)
12 Oct 2014CPOL1 min read 28.8K  
Know how to exclude types from the Model in Entity Framework Code First

Points of Interest

In entity framework code first, the POCO (Plain Old CLR Object) classes are converted to tables. Entity framework looks for different areas of the application to collect all the classes which will be converted to tables in the database.

The followings are the different areas from where the tables are created if any type is found by Entity Framework Code First:

  1. The exposed DbSet<T> collections inside the context class
  2. If there is a reference from one type to other type that is mapped (i.e., the type is reachable from another type)
  3. If there is a reference of a type from any Fluent API method call on the DbModelBuilder

But this is not what we all need every time. Sometimes, we need to exclude some types from the model. We don't want to create tables for all the types which are related to the model in the application.

Entity framework has different options to prevent one type from being included in the model. The following are the ways which explicitly inform Code First to exclude a type:

  • Using [NotMapped] Data Annotation attribute
  • Using Ignore<T>() Fluent API method

Using [NotMapped] Data Annotation Attribute

Use [NotMapped] data annotation attribute to exclude a type from the model as follows:

C#
[NotMapped]
public class DataTransferClass

Using Ignore<T>() Fluent API Method

Use Ignore<T>() Fluent API method to exclude a type from the model as follows:

C#
modelBuilder.Ignore<DataTransferClass>();

Note: You need to include this inside the OnModelCreating() method. You cannot have this setting inside the EntityTypeConfiguration inherited classes.

History

  • 13th October, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)