Tuesday, July 7, 2009

Active Record Pattern Wrapper Using LINQ-to-SQL


Today Entity Data Model (EDM) is becoming more popular because of ADO.NET data services compatibility, but LINQ-to-SQL still is simpler and easy to use. In this article, I will present an approach for LINQ to make it ready for Active Record Pattern. And, there is another project on this approach which you can find at http://www.castleproject.org/activerecord/index.html .


Active Record Pattern is an approach to solve the business layer problem. This approach is explained in details at http://en.wikipedia.org/wiki/Active_record_pattern and in the book of Dino Esposito and Andrea Saltarello: “Microsoft .NET: Architecting Applications for the Enterprise” from MSPress. Even though an experienced architect should be able to find such a reasonable solution by themselves, I believe that such patterns may be a source of inspiration. And remember that these patterns are reasons of experience.

Using the code

There is only one class to make it happen which is complex because of its generic model called BaseDataContext. This class has two generic parameters: TdataContext which is the data context that the LINQ-to-SQL system generates, and TentityType which is an entity contained by the LINQ-to-SQL. This class has the following interface:

void BeginTransaction();
void Clear(); void CommitTransaction(); bool Contains(TEntityType entity);  TDataContext DataContext { get; } void DeleteAllOnSubmit(); void DeleteAllOnSubmit(      System.Collections.Generic.IEnumerable entities); void DeleteOnSubmit(); void DeleteOnSubmit(TEntityType entity); TEntityType Get(); TEntityType Get(Func filter); System.Collections.ObjectModel.ObservableCollection GetAll(); System.Collections.ObjectModel.ObservableCollection         GetAll(Func filter); TEntityType GetBlank();  void InsertAllOnSubmit(); void InsertAllOnSubmit(System.Collections.Generic.IEnumerable entities); void InsertOnSubmit(); void InsertOnSubmit(TEntityType entity); void Load(); void Load(Func filter); void LoadAll(); void LoadAll(Func filter);  System.Collections.ObjectModel.ObservableCollection      MakeAscending(System.Collections.ObjectModel.ObservableCollection list,     Func columnSelector);  System.Collections.ObjectModel.ObservableCollection MakeDescending (System.Collections.ObjectModel.ObservableCollection list,  Func columnSelector);  void OrderByAscending(Func columnSelector); void OrderByDescending(Func columnSelector); void Refresh(); void RefreshAll(); void RollbackTransaction(); void SetBlank(); void SubmitChanges();  System.Data.Common.DbTransaction Transaction { get; } TEntityType Value { get; set; } System.Collections.ObjectModel.ObservableCollection Values { get; set; } System.Data.Linq.Table WholeTable { get; }

The class works in two manners: Loading and Getting:

See full detail: http://www.codeproject.com/KB/linq/Active_Record_Pattern.aspx

No comments: