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:
- The exposed
DbSet<T>
collections inside the context class - If there is a reference from one type to other type that is mapped (i.e., the type is reachable from another type)
- 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:
[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:
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