Không chắc chắn lý do bạn có hai thông số loại trên Kho lưu trữ - điểm là gì?
* Dưới đây là ví dụ điển hình của một Repository NET sử dụng Generics: *
* Đầu tiên, giao diện Repository: *
public interface IRepository<T> where T : class
{
T FindSingle(Expression<Func<T,bool>> predicate);
IQueryable<T> FindAll(); // optional - matter of preference
void Add(T entity);
void Remove(T entity);
}
* Thứ hai, việc thực hiện Generic Repository (EF làm ví dụ): *
public abstract class GenericRepository<T> : IRepository<T>
{
private IObjectSet<T> _ObjectSet; // get this in via DI (for example)
public T FindSingle(Expression<T,bool>> predicate)
{
return _ObjectSet.SingleOrDefault(predicate);
}
// you can figure out how to do the other implementation methods
}
* Sau đó, Repository cụ thể (bạn nên có một cho mỗi gốc tổng hợp, và cũng là một giao diện cho từng kho cụ thể chi tiết các phương pháp cụ thể): *
public EmployeeRepository : GenericRepository<Employee>, IRepository<Employee>
{
// all regular methods (Find, Add, Remove) inherited - make use of them
public Employee FindEmployeeByName(string name)
{
return FindAll().SingleOrDefault(x => x.Name == name);
// or you could do: return FindSingle(x => x.Name == name);
}
}
Cách sử dụng:
IRepository<Employee> repository = new EmployeeRepository<Employee>();
Đừng đi ra ngoài tìm cách để đi quá điên với Generics - người duy nhất bạn cần là để hạn chế Repository được sử dụng bởi một thực thể được đóng gói đằng sau Repository.
Tôi chỉ cần sử dụng where T : class
.
Sử dụng khác where T : IDomainAggregate
hoặc tương tự, để đặt các ràng buộc vào loại thực thể thực thể được phép.
Có quá nhiều lỗi trong mã của bạn (tôi có thể phát hiện 3 ít nhất) để hiểu bạn muốn gì. – leppie
Đọc các ghi chú trên IEmployeeRepo và tôi cũng đã đề cập đến nó sẽ không biên dịch – Jon