5

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

kaya3
  • 47,440
  • 4
  • 68
  • 97
Ion Robu
  • 51
  • 1
  • 3

2 Answers2

15

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"));
magnattic
  • 12,638
  • 13
  • 62
  • 115
  • 1
    I'm using EF 6.0, and this works for all non-explicit implementers: `modelBuilder.Types().Configure(c => c.Ignore(i=> i.EntityId));` – Dan Rayson Mar 25 '15 at 21:46
  • How do I ignore ALL properties of a base class? What happens if I ignore the base type, while declaring entity sets of the sub type? Can I use an `EntityBase` this way, if I don't care about non POCOs? – Shimmy Weitzhandler Jun 06 '17 at 21:51
  • Broken link. Please update if available. Thank you. – Benj Sanders Apr 30 '19 at 17:33
2

You can use the [NotMapped] annotation on the properties, but that will still need to be added for each entity which isn't the same as only specifying it once and having a convention for ignoring it.

Mashton
  • 6,037
  • 2
  • 25
  • 35