4

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?

Dblock247
  • 6,167
  • 10
  • 44
  • 66

1 Answers1

2

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • So let me get this straight. Do I still need to create the Entity POCO class. And then have my other entities inherit from it. Or do I do this instead of my Entity class? – Dblock247 Aug 20 '16 at 20:44
  • After I read your response I came across this. modelBuilder.Ignore();. Would this work for me? Because I may not want every entity create to have these properties. Just the ones I specifically Inherit from Entity. – Dblock247 Aug 20 '16 at 21:08
  • With this you will still have the `Entity` class. I don't have anything to test on right now, but I suspect that `Ignore` will cascade down to all of your entities in the same way you had the initial problem. – DavidG Aug 20 '16 at 23:10
  • I have tried it. It works. I don't mind having the entity class as it is good for documentation. I just didn't want it to generate a table in the database. But i wanted to be able to configure the inherited fields. – Dblock247 Aug 21 '16 at 00:12