存储库模式:如何实现接受业务实体表达式的DeleteWhere
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 的表达式,但我希望我的存储库将 DBEntities 隐藏在其中。
请指教。欢迎任何想法。
PS我正在使用.NET 3.5(但4.0的解决方案也可以接受),ORM - Linq2Sql
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想,我找到了一个很好的解决方案,这是 RepositoryBase 类的一个新方法:
如果您在这里看到任何缺点,请指出我。
Guess, I've found a good solution, here is a new method for RepositoryBase class:
Please point me if you see any drawbacks here.