如何实现Repository FindAll()方法?

我有以下存储库模式。 要求是“查找所有者姓名为Lijo的所有帐户”。 所以,我需要编写一个FindAll函数。 怎么写这个function?

限制是:

1)客户端“BankAccountService”不应使用“DBML_Project”中的类。

2)我们不应该使用GetAll方法来退出完整的帐户列表,然后进行过滤。

注意:我在处理多态性问题时遇到了这个问题:ORM实体是域实体还是数据实体?

namespace ApplicationService_Bank { public class BankAccountService { RepositoryLayer.ILijosBankRepository accountRepository = new RepositoryLayer.LijosSimpleBankRepository(); public void FreezeAllAccountsForUser(string userName) { //Should not use assembly 'DBML_Project'. IEnumerable accountsForUserWithNameLIJO = null; //accountsForUserWithNameLIJO = accountRepository.FindAll(p => p.BankUser.Name == "Lijo"); } } } namespace RepositoryLayer { public interface ILijosBankRepository { List GetAll(); IEnumerable FindAll(System.Func predicate); void SubmitChanges(); } public class LijosSimpleBankRepository : ILijosBankRepository { private IBankAccountFactory bankFactory = new MySimpleBankAccountFactory(); public System.Data.Linq.DataContext Context { get; set; } public virtual List GetAll() { List allItems = Context.GetTable().ToList(); List bankAccounts = new List(); foreach (DBML_Project.BankAccount acc in allItems) { DomainEntitiesForBank.IBankAccount theAccount = bankFactory.CreateAccount(acc.AccountType, acc.BankAccountID, acc.Status, acc.OpenedDate, acc.AccountOwnerID); bankAccounts.Add(theAccount); } return bankAccounts; } public IEnumerable FindAll(System.Func predicate) { //Where var results = Context.GetTable().Where(predicate); return results; } public virtual void SubmitChanges() { Context.SubmitChanges(); } } } 

读:

  1. 返回IEnumerable 与IQueryable

  2. 如何设计Repository模式以便以后轻松切换到另一个ORM?

一种简单的方法是手动构建查询:

 public class SearchCriteria { public string Name { get; set; } // ...more } public IEnumerable FindAll(SearchCriteria criteria) { IQueryable entities = _datasource.Entities; // replace with your L2S equivalent if (criteria.Name != null) entities = entities.Where(e => e.Name == criteria.Name); // ...more return entities; } 

如果您不想直接返回生成的对象,请在返回之前映射到其他对象:

 return Map(entities); // IEnumerable Map(IEnumerable entities)