0

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

约束是:

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<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. 返回 IEnumerable<T> 与 IQueryable<T>

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

4

1 回答 1

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)
于 2012-06-29T12:30:45.267 回答