Tell EF6 not to save the base class, but set the FluentAPI flags

I have a base class called "Entity" in which I put the standard fields that an entity should ever inherit (for example, Id, CreateAt, UpdateAt). I prefer to use FluentAPI, as it is considered more powerful than annotations, and allows you to use pure easily readable POCO classes. Is there a way to configure the attributes on these fields in a free api for the parent entity class and inherit it, but also not generate a table in the database for the POCO Entity class?

+4
source share
1 answer

The normal configuration of the object will be something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Planet>().HasKey(b => b.Id);
}

However, as you noticed, this will also register the type as part of your model. Entity Framework 6 introduced a method DbModelBuilder.Types<T>that according to the docs:

Begins setting up a lightweight convention that applies to all objects and complex model types that inherit or implement the type specified by a common argument. This method does not register types as part of the model.

This means that you can configure the base entity class as follows:

modelBuilder.Types<Entity>().Configure(c =>
{
    c.HasKey(e => e.Id);
});

Which saves you from having to do this for every type that inherits from Entity.

+1
source

Source: https://habr.com/ru/post/1651847/


All Articles