Reputation: 383
I have many tables in DB that share the same schema; Example: Table1 (id, nameE, nameF) Table2 (id, nameE, nameF)...
Using EF/Asp.net Core3+ to retrieve the data, I have done this:
my DbContext example:
public DbQuery<ValueList1> Table1 { get; set; }
public DbQuery<ValueList2> Table2 { get; set; }
now my Model ValueList1 and ValueList2 contains the same parameters
[Table("Table1")]
public class ValueList1
{
public int id { get; set; }
public string nameE{ get; set; }
public string nameF{ get; set; }
}
[Table("Table2")]
public class ValueList2
{
public int id { get; set; }
public string nameE{ get; set; }
public string nameF{ get; set; }
}
I can successfully retrieve the data _dbContext.Table1; and _dbContext.Table2;
My question: How can I use one model instead of duplicating and having duplicate files.
I have tried that but it failed on line [Table("Table1, Table2")]
public DbQuery<ValueList> Table1 { get; set; }
public DbQuery<ValueList> Table2 { get; set; }
[Table("Table1, Table2")]
public class ValueList1
{
public int id { get; set; }
public string nameE{ get; set; }
public string nameF{ get; set; }
}
Upvotes: 0
Views: 41
Reputation: 89316
Adding to @WilliamChow's answer, you can then put properties on your DbContext like
public IQueryable<ValueList> Table1 => this.Set<Table1>();
public IQueryable<ValueList> Table2 => this.Set<Table2>();
Since IQueryable supports covariance.
Upvotes: 0
Reputation: 29
To be the base class for same properties, and inherite the base class
public class ValueList1
{
public int id { get; set; }
public string nameE{ get; set; }
public string nameF{ get; set; }
}
[Table("Table 1")]
public class Table1 : ValueList1
{
}
Upvotes: 2