Multiple tables with the same POCO class

I have an existing database where I have four identical and unrelated tables.

I want to use the same POCO class to describe all four without creating duplicates of the same class.

This is what my context looks like:

class StatsContext : DbContext { // [MagicTableAttribute( "map_ratings_vsh" )] -- does something like this exist? public DbSet<MapRatings> MapRatingsVSH { get; set; } public DbSet<MapRatings> MapRatingsJump { get; set; } // 2 more tables using same class } class MapRatings { public string SteamID { get; set; } public string Map { get; set; } public int Rating { get; set; } [Column( "rated" )] public DateTime Time { get; set; } } 

My problem is that the existing tables are called "map_ratings_vsh" and "map_ratings_jump", and I cannot use TableAttribute data annotations because they can only be used in the class.

Is there any other way - maybe a quick api - to describe my scheme?

+4
source share
3 answers

One way to find a solution is to use inheritance.

 [Table("map_ratings_vsh")] public class MapRatingsVSH : MapRatingsBase {} [Table("map_ratings_jump")] public class MapRatingsJump : MapRatingsBase {} public class MapRatingsBase { public string SteamID { get; set; } public string Map { get; set; } public int Rating { get; set; } [Column( "rated" )] public DateTime Time { get; set; } } 

Then you can create your DbContext as follows:

 public class StatsContext : DbContext { public DbSet<MapRatingsVSH> MapRatingsVSH { get; set; } public DbSet<MapRatingsJump> MapRatingsJump { get; set; } } 

EF should not have any problems, understanding that these are two different tables, even if the implementation will be in one place ( MapRatingsBase )

+7
source

You can freely use api to map some properties to one table and other properties in another table as follows:

 modelBuilder.Entity<TestResult>() .Map(m => { m.Properties(t => new { /* map_ratings_vsh columns */ }); m.ToTable("map_ratings_vsh"); }) .Map(m => { m.Properties(t => new { /* map_ratings_jump columns */ }); m.ToTable("map_ratings_jump"); }); 
+3
source

I used this method in the past to return data using a stored procedure or view, and then provide the AddEntity or SaveEntity method in the DbContext implementation that is stored in the entity in question

0
source

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


All Articles