Search code examples
c#sql-serverentity-frameworklinqlinq-to-entities

Accessing different tables using the same model Entity framework С#


Faced with the following problem: I have two tables and one model that fits them. I think it is wrong to create a separate identical model for the second table, although it is a working method. Can you tell me how to build the logic to access either the first table or the second?


Solution

  • While I understand the premise behind this, I do not think it is possible to access two tables using one model in EF Core (nor do I think it is a good idea), because the Table attribute cannot be duplicated.

    However, you can get over this limitation if you implement inheritance.

    [Table("Table1")]
    public class Model1 : MyBaseModel
    {
    }
    [Table("Table2")]
    public class Model2 : MyBaseModel
    {
    }
    public class MyBaseModel
    {
        public int ID { get; set; }
    }
    

    The properties from MyBaseModel will then be inherited to both Model1 and Model2 classes. Assuming that these models have the same column named ID you would be able to access the two tables using two different classes (albeit, with one base model) this way.