【发布时间】:2017-01-31 15:41:06
【问题描述】:
我有两个复杂的类:
public class BaseRepository<EntityType> where EntityType : class
{
protected northwindDataContext context = new northwindDataContext();
public EntityType Get(object id)
{
return context.Set<EntityType>().Find(id);
}
public EntityType Save(EntityType entity)
{
// Do generic save things
}
}
public class BaseService<EntityType> where EntityType : class
{
public BaseRepository<EntityType> repo = new BaseRepository<EntityType>();
public EntityType Get(object id)
{
// Do generic get entities
return repo.Get(id);
}
}
然后我有多个“服务”类,有时(并非总是)我需要“替换”存储库以添加一些“额外”功能。
public class UserRepository : BaseRepository<User>
{
public User Get(object id)
{
// Do specific user get including Role DP
return context.Users.Include("Role").Find(id);
}
}
public class UserService : BaseService<User>
{
public UserRepository repo = new UserRepository();
}
使用这种格式,UserService 实例调用 BaseRepository.Get() 而不是 UserRepository.Get()。
我想要做的唯一方法是复制这样的代码:
public class UserService : BaseService<User>
{
public UserRepository repo = new UserRepository();
public User Get(object id)
{
// This call to UserRepository.Get()
return repo.Get(id);
}
}
真正的问题是我有 29 个“存储库”,所以我需要添加“Get(int)”、“Get(predicate)”、“Save(entity)”、“Save(IEnumerable)”、“Delete( entity)" 和 "Delete(IEnumerable)",这会产生一种尴尬的代码。
有没有办法替换BaseService中的“repo”属性,让BaseService方法调用repo子类?
【问题讨论】:
标签: c# entity-framework