【发布时间】:2014-05-26 14:29:03
【问题描述】:
我正在尝试制作发票管理应用程序。
创建 DAL 对象时,我必须为每个表重复 Add 和 Delete 函数。
例如:
public class MyDBProcessor :IMyDBProcessor {
tpEntities tp=new tpEntities();
public void AddCustomerToDB(tblCustomers Customer) { tp.tblCustomers.Add(Customer); tp.SaveChanges();}
public void AddOrderToDB(tblOrders Order) { tp.tblOrders.Add(Order); tp.SaveChanges(); }
public tblCustomers GetCustomerFromDB(string CustomerID) { return tp.tblCustomers.Where(x => x.ID == CustomerID); }
public tblOrders GetOrderFromDB(string OrderID) { return tp.tblOrders.Where(x => x.ID == OrderID); }
}
这很令人沮丧,因为有很多桌子。我想像这样更改 DAL 接口:
public interface IMyGenericDBProcessor {
void AddToDB<T>(T Record);
T GetFromDB<T>(int RecordID);
}
所以,当我将数据库引擎 MySQL 更改为 SQL Server 时,反之亦然。如何编写实现IMyGenericDBProcessor 的类?
谢谢,
【问题讨论】:
-
如果您没有真正的要求来支持多个数据库,那么仅使用抽象来支持多个数据库确实是矫枉过正。在现实世界的应用程序中,您可能只是将每个 DAL 类的内容转换为使用其他数据库引擎。另一方面,如果您想使用抽象来降低复杂性,请提出一个新问题,因为该方法与当前问题不同。至于当前的问题,存储库模式是一种方法:blog.gauffin.org/2013/01/repository-pattern-done-right
-
@jgauffin 你说我需要一个完整的新 DAL 对象?
-
我不会将所有数据库访问代码放到一个类中。随着应用程序的增长,维护起来会很痛苦。
-
您正在使用实体框架?在我看来,这已经是一个 DAL。您可能需要数据传输对象来抽象信息,或将其布置在不同的模式中,但如果您正在连接自定义模型 数据库/DAL 层,则不应使用 EF(因为为什么要使用?)
-
这很好,但是如果您的检查是特定的,那么在通用 DBProc 中编写它们会不会很困难?我的意思是,如果它是通用的,它是——对吗?无论如何,祝你好运:)
标签: c# entity-framework data-access-layer