Сопоставить несколько сущностей с абстрактным базовым классом EF4 или интерфейсом? - PullRequest
1 голос
/ 25 сентября 2011

У меня есть несколько таблиц в БД, которые идентичны с точки зрения структуры столбцов.

Я хотел бы смоделировать это в EF4, чтобы они все наследовали от одного абстрактного базового класса, поэтому я могуписать общие методы и т. д.

Я пробовал абстрактный базовый класс, но это означает, что мне нужно добавить свойство для каждой сущности, которой нет в базовом классе.Также кажется, что я теряю свои коллекции, так как каждая из них теперь является коллекцией базового типа?

Я могу добавить частичные классы и наследовать каждый из общего интерфейса?

например

Table 1     Table 2     Table 3
Id          Id          Id
Month1      Month1      Month1
Month2      Month2      Month2
Month3      Month3      Month3
Quarter2    Quarter2    Quarter2
Quarter3    Quarter3    Quarter3
Quarter4    Quarter4    Quarter4

Как я могу иметь базовый класс или интерфейс под названием "таблица", чтобы я мог писать все свои методы против этого, а не против каждой отдельной таблицы?

1 Ответ

0 голосов
/ 25 сентября 2011

Если вы вынуждены хранить отдельные таблицы и просто хотите иметь возможность писать общие методы, вы можете использовать методы интерфейса и расширения, как показано ниже:

public interface ITableBase{
    int Id{ get; set; }
    // other properties
    void Method1();
    int Method2();
    string Method3(int some_arguments);
}

public partial class Table1 : ITableBase{
    // implement ITableBase and other properties and methods
}

public partial class Table2 : ITableBase{
    // implement ITableBase and other properties and methods
}

public partial class Table2 : ITableBase{
    // implement ITableBase and other properties and methods
}

static public class ITableBaseExtensions{
    static public string GetIdAsString(this ITableBase table){
        return table.Id.ToString();
    }
    static public int UsingMethod2(this ITableBase table){
        var i = table.Method2();
        return i * 5 + 9 - 14 / 3 % 7 /* etc... */;
    }
    static public void AddingNewMethodToTables(this ITableBase table, string some_string,
        int some_int, YourType any_other_parameter /* etc... */ ){
        // implement the method you want add to all Table classes
    }
    // 
    // You can add any method you want to add to table classes, here, as an Extension method
    //
}

А у потребителей можно вызывать все методы, определенные в ITableBaseExtensions классе для всех таблиц:

public class MyConsumer{
    public void MyMethod(){
        Table1 t1 = new Table1();
        Table1 t2 = new Table2();
        Table1 t3 = new Table3();

        t1.UsingMethod2(); // will be called from ITableBaseExtensions
        t1.Method2(); // will be called from ITableBase - must implemented in Table1 class

        t2.Method3(some_argument); //  will be called from ITableBase - must implemented in Table2 class
        t2.GetIdAsString(); // will be called from ITableBaseExtensions

        // etc.
    }
}
...