讲解ASP.NET中LINQ to SQL 实现数据访问通用基类(3)
如何避免这些问题
在相当多的在线调研后,我实现了一个RepositoryBase类,使用他您可以快速实现您的数据层,所示为测试通过的例子。 首先,用对象关系映射器(译者注:Visual Studio自带工具)来产生序列化的LINQ实体:在Visual Studio中打开dbml文件,在空白区域某处左键单击,弹出属性窗口,设置“Serialization Mode属性”为“Unidirectional”。
现在您可以继承RepositoryBase实现您自己的Repository:
view plaincopy to clipboardprint?
1. public class CustomersRepository :
2. //derive from RepositoryBase with the entity name and
3. //data context as generic parameters
4. DeverMind.RepositoryBase
5. {
6. override protected Expression<Func<Customer, bool>> GetIDSelector(int ID)
7. {
8. //ID needs to be the entity's ID column name
9. return (Item) => Item.ID == ID;
10. }
11. }
12. public partial class Customer
13. {
14. public static RepositoryBase CreateRepository()
15. {
16. //create and return an instance of this entity type's repository
17. return new CustomersRepository();
18. }
19. }
您的每一个实体的类型都照这样做,你就拥有了一个工作在断开模式下无缝数据层。您继承Repository的类自动执行下列方法:
作为锦上添花的功能,在应用程序调试的过程中,你还可以通过输出控制台看到执行对数据库的操作的SQL命令。这多亏了被用于RepositoryBase的SQL调试输出的Kris Vandermotten 方便的DebuggerWriter组件(译者注:外国人就是绅士)!