存储库模式:如何实现接受带有Business实体的表达式的DeleteWhere

时间:2010-12-17 17:13:33

标签: linq-to-sql design-patterns repository

public interface IRepository<T>// : IDisposable
    where T : IEntity
{
    IQueryable<T> GetAll();
    void Save(T entity);
    void Delete(int id);
    void Delete(T entity);
}

public abstract class RepositoryBase<T, TDb> : IRepository<T>
    where T : IEntity
    where TDb : class, IDbEntity, new()
{
    protected abstract Table<TDb> GetTable();

    public void Delete(int id)
    {
        TDb dbEntity = GetDbEntity(id);

        if (dbEntity == null)
        {
            throw new MyException(...);
        }

        GetTable().DeleteOnSubmit(dbEntity);

        Context.SubmitChanges();
    }

    //  and other methods...   
}

现在有必要实现通过表达式删除实体的方法。我想在IRepository中使用以下方法:

void DeleteWhere(Expression<Func<IEntity, bool>> exprFoeBusinessEntity);

这里的问题是实现看起来像这样:

void DeleteWhere(Expression<Func<IEntity, bool>> exprFoeBusinessEntity);
{
    Expression<Func<IDbEntity, bool>> exprFoeDbEntity 
        = exprWhere=> ... // How to convert exprFoeBusinessEntity into exprFoeDbEntity

    GetTable().DeleteAllOnSubmit(GetTable().Where(exprForDbEntity)));
}

我不知道如何将业务实体的表达式转换为db-entities的表达式......

我可以轻松地更改方法以接受带有db-entities的表达式,但我希望我的Repository隐藏DBEntities。

请指教。欢迎任何想法。

P.S。我正在使用.NET 3.5(但4.0的解决方案也可以接受),ORM - Linq2Sql

1 个答案:

答案 0 :(得分:0)

猜猜,我找到了一个很好的解决方案,这里是RepositoryBase类的一个新方法:

    public void Delete(IQueryable<T> entities)
    {
        IQueryable<TDb> dbEntities = GetTable()
            .Where(
                dbEntity => entities.Where(entity => entity.Id == dbEntity.Id).Count() > 0
                  )
            ;
        GetTable().DeleteAllOnSubmit(dbEntities);
    }

如果您在此处看到任何缺点,请指出我。