我正在关注这个网站:http://deviq.com/repository-pattern/
其中包含使用DB上下文的存储库模式的示例.我正在尝试用列表实现这个通用的Repository类(我想要Repository类.这是我的要求).但是,我遇到了Find方法的问题.
public class Repository: IRepository where T : class { private List context; virtual public T Find(int id) { // I can't figure out a way to make this work with the list of a generic type } }
这甚至可以使用ID参数在List.Find()中生成谓词吗?我猜不是,但有什么选择?
您可以声明T具有Id属性,其类似于:
public interface IEntity { int Id { get; } } public class Repository: IRepository where T : class, IEntity { private List context; virtual public T Find(int id) { return context.SingleOrDefault(p => p.Id == id); } }
如果您无法控制T的类型以便应用界面,另一个选择是强制您的实施者进行艰苦的工作.
public abstract class Repository: IRepository where T : class { private List context; public virtual public T Find(int id) { return context.FirstOrDefault(x => GetId(x) == id); } public abstract int GetId(T entity); }
一个示例实现可能是
// entity public class Stooge { public Stooges MoronInQuestion {get;set;} public double MoeEnragementFactor {get;set;} public void PloinkEyes() { /*snip*/ } public void Slap() { /*snip*/ } public void Punch() { /*snip*/ } // etc } // enum for an Id? It's not that crazy, sometimes public enum Stooges { Moe = 1, Larry = 2, Curly = 3, Shemp = 4, Joe = 5, /* nobody likes Joe DeRita */ //CurlyJoe = -1, } // implementation public class StoogeRepository : IRepository{ public override int GetId(Stooge entity) { if(entity == null) throw new WOOWOOWOOException(); return (int)entity.MoronInQuestion; } }