Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Ignore property by conventions

I have a code-first model where all entities are derived from a Entity base class. I have a property IsDeleted in base class which I want to ignore in all entities (I cannot remove/comment IsDeleted property since base class is used in many projects). Is there a way to configure modelBuilder to ignore this property form all entities (by conventions, I think), without to specify modelBuilder.Entity<...>().Ignore(l => l.IsDeleted) for all entities from my model?

Thanks, Ion

like image 430
Ion Robu Avatar asked Feb 26 '14 10:02

Ion Robu


People also ask

What is OnModelCreating in Entity Framework?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.

What is NotMapped attribute?

The NotMapped attribute is used to specify that an entity or property is not to be mapped to a table or column in the database. In the following example, the AuditLog class will not be mapped to a table in the database: public class Contact. { public int ContactId { get; set; }

What is lazy loading EF core?

Lazy loading means that the related data is transparently loaded from the database when the navigation property is accessed.


1 Answers

You can do this using the new EF 6.1 Custom Code First Conventions:

modelBuilder.Types().Configure(c => c.Ignore("IsDeleted"));

This will ignore any property of the name IsDeleted in any of your types.

If you only want to do this for classes inheriting a certain base class, you can do:

modelBuilder.Types()
            .Where(t => t.IsSubclassOf(typeof(MyBaseClass)))
            .Configure(c => c.Ignore("IsDeleted"));
like image 164
magnattic Avatar answered Oct 05 '22 00:10

magnattic