Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can fluent API set NotMapped on all entities that inherit from a base class?

Sometimes it's useful to derive my entities from a base class like this:

public abstract class DestructableBase : IDestructable
{
   /// <summary>
   /// If true, this object should be deleted from the database.
   /// </summary>
   [NotMapped]
   public bool _destroy { get; set; }
}

This allows a web client to mark an entity as needing to be deleted when data is posted back to the server. Obviously I do not wish to record such a property in the database though, so I use the [NotMapped] attribute.

I've begun using the fluent API more and more to do my configurations though and would like to stop using data annotations. Is there a way to use the fluent API to do this without having to set Ignore() on every entity individually? Or is there a better way altogether?

like image 524
C.J. Avatar asked Sep 17 '25 11:09

C.J.


1 Answers

You can try to use this class as a base class for your entity configurations:

public class DestructableBaseConfiguration<TEntity> : EntityTypeConfiguration<TEntity>
    where TEntity : DestructableBase
{
    public DestructableEntityConfiguration()
    {
        Ignore(e => e._destroy);
    }
} 

Now every other entity derived from DestructableBase needs entity configuration class derived from DestructableBaseConfiguration. You will register your configurations to modelBuilder in OnModelCreating.

like image 158
Ladislav Mrnka Avatar answered Sep 19 '25 07:09

Ladislav Mrnka