简体   繁体   中英

Tell EF6 Not to Persist Base Class but set FluentAPI contrains

I have a base class called "Entity" in which I put standard fields that should be inherited by ever entity (ex. Id, CreateAt, UpdateAt). I prefer to use FluentAPI as it is said to be more powerful then annotations and it enables clean easily readable POCO classes. Is there a way I can set up attributes on those fields in fluent api for the parent entity class and have it inherited but also not generate a table in the database for the "Entity" POCO class?

A normal entity configuration would be something like this:

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

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

Begins configuration of a lightweight convention that applies to all entities and complex types in the model that inherit from or implement the type specified by the generic argument. This method does not register types as part of the model.

That means you can configure your base entity class like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM