开发者

Repository pattern: how to implement DeleteWhere that accepts expression with Business entities

开发者 https://www.devze.com 2023-01-31 16:37 出处:网络
public interface IRepository<T>// : IDisposable where T : IEntity { IQueryable<T> GetAll(); void Save(T entity);
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...   
}

For now it is necessary to implement method that deletes entities by expression. I would like to have开发者_StackOverflow the following method in IRepository:

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

The problem here is that implementation would look like this:

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

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

And I don't know how to convert expression for business entities into expression for db-entities...

I could easily change method to accept expression with db-entities, but I would like my Repository to hide DBEntities inside.

Please advise. Any thoughts are welcome.

P.S. I am working with .NET 3.5 (but solutions for 4.0 are also acceptable), ORM - Linq2Sql


Guess, I've found a good solution, here is a new method for RepositoryBase class:

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

Please point me if you see any drawbacks here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号