Entity Framework 4.1 Code First: Get all objects with a specific base class

I have a DbContext with setting up different DbSet<T> with all types that come from the same base class:

 public class Foo : Entity { } public class Bar : Entity { } MyDbContext : DbContext { public DbSet<Foo> Foos { get; set; } public DbSet<Bar> Bars { get; set; } } 

Is it possible to get all objects that have an Entity base class in a single query, for example:

 DbContext.Set<Entity>(); // doesn't work 

I tried to enter an explicit DbSet<Entity> in the DbContext, but this results in one large table for all objects in the database.

Additional question: if it works somehow, what about interface requests?

Edit:

I followed the instructions on the Ladislav Mrnka link and made my comparisons as follows:

 MyDbContext : DbContext { public DbSet<Entity> Entities { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Foo modelBuilder.Entity<Foo>().Map(x => { x.MapInheritedProperties(); x.ToTable("Foo"); }) .HasMany(x => x.Tags).WithMany(); modelBuilder.Entity<Foo>() .Property(x => x.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); // Bar // same thing for Bar and a bunch of other Entities base.OnModelCreating(modelBuilder); } } 

Now it causes an error

The "Id" property is not a declared property in the "Foo" type. Verify that the property has not been explicitly excluded from the model using the Ignore or NotMappedAttribute annotation. Verify that this is a valid primitive property.

I also tried to explicitly set the key to the Id property:

 modelBuilder.Entity<Foo>().Map(x => {...}) .HasKey(x => x.Id) .HasMany(x => x.Tags).WithMany(); 

What am I missing?

+7
source share
2 answers

You need to enter TPC Inheritance . After that, DbContext.Set<Entity>() will work, and you will still have a table for each object.

+4
source

Just in time for your problem in the "Edit" section:

The error message indicates that you have an Id key property in the Entity base class. Then you need to configure the key property in this class, and not in the derived class Foo :

 modelBuilder.Entity<Entity>() .Property(x => x.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); 
+2
source