Change the dynamic mapping of the Fluent API

Our project first uses the Entity Framework Code. We want to have an instance where a very simple POCO is a lot of tables in a database. It is part of the horizontal partitioning strategy in SQL Azure. SQL Azure does not support filegroups, so it does not support typical partitioning. There will be a very large number of tables, so using the UNION ALL view as a partitioned view through CHECK CONSTRAINT on the base tables will be impossible.

Thus, we would prefer to display the display as needed at runtime. However, this happens in the OnModelCreating event of the DbContext class using code such as

modelBuilder.Entity<EntityName>().ToTable("foo", "bar"); 

. Is it possible to perform this mapping inside a factory? We would prefer to supply metadata to the factory and then use the Fluent API, rather than matching one-to-one between POCO and the table via ModelBuilder.

+3
source share
1 answer

You can add a constructor to your DbContext derivative by having two string arguments for the table name and DbContext name. You can store names in member variables and use them in the ToTable method.

DbModel is created when it is really necessary, so the constructor always runs before the OnModelCreating event. (This does not always happen in derived classes, but this is a different topic).

As an optimization, you can cache compiled DbModel and build a DbContext constructor that accepts a DbCompiledModel .

+5
source

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


All Articles