我在db中有多个表,这些表在列结构方面是相同的。
我想在EF4中建模,以便它们都从一个抽象基类继承,所以我可以编写常用方法等。
我尝试过一个抽象基类,但这意味着我需要为不在基类中的每个实体添加一个属性。它似乎也丢失了我的收藏品,因为每个收藏品现在都是基本类型的集合?
我可以添加部分类并从公共接口继承它们吗?
e.g。
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
我如何拥有一个名为“table”的基类或接口,以便我可以针对每个表编写所有方法而不是针对每个表?
答案 0 :(得分:0)
如果您强制保留单独的表,并且您只想写 常用方法,您可以使用如下所示的接口和扩展方法:
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.
}
}