Multiple Tables With Same Structure Entity Framework
Asked Answered
P

3

10

We have a database with multiple tables with Same structure

Table 1

Key ID ........

Table 2

Key ID .......

The number of tables can be dynamic based on configuration.

I am trying to upgrade the data access Layer to Entity framework. I have created one class representing the structure of the table. My Plan is to use the same class for all the tables with same structure. Bubt I could not find enough information on how to do this. What I understood is that I can map one class to one table only.

Is there any way to achieve this using entity framework?

Posticous answered 14/7, 2016 at 11:10 Comment(3)
Why not normalise your database tables instead?Tracytrade
Create a single view for all tables with the same structure. Map the EF entity to this view.Jeanne
@IntoNET:The database is quite complicated and this can not be changed.Posticous
P
33

The easy way: have an abstract base class with all the properties, and map concrete types:

public abstract class BaseClass
{
   public int Id { get; set; }
   public string StringField { get; set; }
   /* Other fields */ 
}

[Table("Table1")]
public class Table1 : BaseClass
{
}

[Table("Table2")]
public class Table2 : BaseClass
{
}

I'm not answering whether that design is good or bad (I wouldn't say I like it as you explained it), I'm just answering the question

Phew answered 14/7, 2016 at 11:23 Comment(2)
Thanks for your reply. Will try this.Posticous
I've settled on doing this but with an interface instead of an abstract class.Honorable
A
0

And now for a completely different approach which I have used successfully in EF Core:

Create a parameterized stored procedure which uses some dynamic SQL to return the actual table you want and use the FromSql feature.

Altar answered 22/12, 2018 at 10:33 Comment(0)
S
0

Since EF Core 7.0 the new TPC (Table per concrete type) mapping scheme seems to be relevant to this issue. When the TPC mapping scheme is invoked Each concrete class can map to an individual table without any weird foreign key references or constraint issues. I found details here

Swineherd answered 10/9, 2024 at 13:2 Comment(1)
That doesn't map one class to multiple tables.Angadreme

© 2022 - 2025 — McMap. All rights reserved.