如何实现Repository FindAll()方法?

时间:2012-06-29 11:47:15

标签: c# .net design-patterns linq-to-sql domain-driven-design

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

约束是:

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

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

注意:我在处理问题Polymorphism: Is ORM entity a Domain Entity or Data Entity?

时遇到了这个问题

CODE

namespace ApplicationService_Bank
{
public class BankAccountService
{
    RepositoryLayer.ILijosBankRepository accountRepository = new RepositoryLayer.LijosSimpleBankRepository();

    public void FreezeAllAccountsForUser(string userName)
    {
        //Should not use assembly 'DBML_Project'.

        IEnumerable<DomainEntitiesForBank.IBankAccount> accountsForUserWithNameLIJO = null;
        //accountsForUserWithNameLIJO = accountRepository.FindAll(p => p.BankUser.Name == "Lijo");
    }

}

}


namespace RepositoryLayer
{
public interface ILijosBankRepository
{
    List<DomainEntitiesForBank.IBankAccount> GetAll();
    IEnumerable<DBML_Project.BankAccount> FindAll(System.Func<DBML_Project.BankAccount, bool> predicate);
    void SubmitChanges();
        }

public class LijosSimpleBankRepository : ILijosBankRepository
{

    private IBankAccountFactory bankFactory = new MySimpleBankAccountFactory();
    public System.Data.Linq.DataContext Context
    {
        get;
        set;
    }

    public virtual List<DomainEntitiesForBank.IBankAccount> GetAll()
    {

        List<DBML_Project.BankAccount> allItems = Context.GetTable<DBML_Project.BankAccount>().ToList();
        List<DomainEntitiesForBank.IBankAccount> bankAccounts = new List<DomainEntitiesForBank.IBankAccount>();
        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<DBML_Project.BankAccount> FindAll(System.Func<DBML_Project.BankAccount, bool> predicate)
    {
        //Where
        var results = Context.GetTable<DBML_Project.BankAccount>().Where(predicate);
        return results;
    }

    public virtual void SubmitChanges()
    {
        Context.SubmitChanges();
    }

}

}

读:

  1. Returning IEnumerable<T> vs. IQueryable<T>

  2. how to design Repository pattern to be easy switch to another ORM later?

1 个答案:

答案 0 :(得分:3)

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

public class SearchCriteria
{
    public string Name { get; set; }
    // ...more
}

public IEnumerable<Entity> FindAll(SearchCriteria criteria)
{
    IQueryable<Entity> 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<CustomObject> Map(IEnumerable<Entity> entities)