我正准备开始一个新的asp.net web项目,我将转向LINQ-to-SQL.我已经完成了一些工作,使用Mike Hadlow发现的一些信息来设置我的数据层,这些信息使用Interface和泛型为数据库中的每个表创建一个Repository.起初我认为这是一个有趣的方法.但是,现在我认为创建一个基本Repository类并继承它以为我需要访问的表创建一个TableNameRepository类可能更有意义.
哪种方法允许我以干净的可测试方式添加特定于表的功能?这是我的Repository实现以供参考.
public class Repository: IRepository where T : class, new() { protected IDataConnection _dcnf; public Repository() { _dcnf = new DataConnectionFactory() as IDataConnection; } // Constructor injection for dependency on DataContext // to actually connect to a database public Repository(IDataConnection dc) { _dcnf = dc; } /// /// Return all instances of type T. /// ///IEnumerable public virtual IEnumerableGetAll() { return GetTable; } public virtual T GetById(int id) { var itemParam = Expression.Parameter(typeof(T), "item"); var whereExp = Expression.Lambda > ( Expression.Equal( Expression.Property(itemParam, PrimaryKeyName), Expression.Constant(id) ), new ParameterExpression[] { itemParam } ); return _dcnf.Context.GetTable ().Where(whereExp).Single(); } /// /// Return all instances of type T that match the expression exp. /// /// ///IEnumerable public virtual IEnumerableFindByExp(Func exp) { return GetTable.Where (exp); } /// See IRepository. ///public virtual T Single(Func exp) { return GetTable.Single(exp); } /// See IRepository. /// public virtual void MarkForDeletion(T entity) { _dcnf.Context.GetTable().DeleteOnSubmit(entity); } /// /// Create a new instance of type T. /// ///T public virtual T Create() { //T entity = Activator.CreateInstance(); T entity = new T(); GetTable.InsertOnSubmit(entity); return entity; } /// See IRepository. public virtual void SaveAll() { _dcnf.SaveAll(); } #region Properties private string PrimaryKeyName { get { return TableMetadata.RowType.IdentityMembers[0].Name; } } private System.Data.Linq.TableGetTable { get { return _dcnf.Context.GetTable (); } } private System.Data.Linq.Mapping.MetaTable TableMetadata { get { return _dcnf.Context.Mapping.GetTable(typeof(T)); } } private System.Data.Linq.Mapping.MetaType ClassMetadata { get { return _dcnf.Context.Mapping.GetMetaType(typeof(T)); } } #endregion }
Frederik Ghe.. 5
您不应为每个表创建存储库.
相反,您应该为域模型中存在的每个"实体根"(或聚合根)创建一个存储库.您可以在此处了解有关该模式的更多信息并查看工作示例:
http://deviq.com/repository-pattern/
您不应为每个表创建存储库.
相反,您应该为域模型中存在的每个"实体根"(或聚合根)创建一个存储库.您可以在此处了解有关该模式的更多信息并查看工作示例:
http://deviq.com/repository-pattern/