Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Tables With Same Structure Entity Framework

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?

like image 922
Satish Avatar asked Jul 14 '16 11:07

Satish


2 Answers

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

like image 167
Jcl Avatar answered Sep 18 '22 04:09

Jcl


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.

like image 34
Greg Gum Avatar answered Sep 19 '22 04:09

Greg Gum