我有一些通常看起来像这样的存储库
public class DepartmentsRepository
{
private PersonnelActionFormDataContext db = new PersonnelActionFormDataContext();
/// <summary>
/// returns all departments
/// </summary>
/// <returns>an iquerable of all departments</returns>
public IQueryable<Department> GetAll()
{
return db.Departments;
}
/// <summary>
/// Get department by id
/// </summary>
/// <param name="id">id of the department</param>
/// <returns>a null department if nothing is found</returns>
public Department Get(int id)
{
return db.Departments.SingleOrDefault(d => d.id == id);
}
/// <summary>
/// Get department by department name
/// </summary>
/// <param name="department">name of the department</param>
/// <returns>a null department if nothing is found</returns>
public Department Get(string department)
{
return db.Departments.SingleOrDefault(d => d.DepartmentName == department);
}
/// <summary>
/// Add a department
/// </summary>
/// <param name="department"></param>
public void Add(Department department)
{
db.Departments.InsertOnSubmit(department);
}
我想要某种通用基类可以节省一些打字,所以我从这里开始
public class GenericRepository<T>
{
private PersonnelActionFormDataContext db = new PersonnelActionFormDataContext();
public IQueryable<T> GetAll()
{
return db.
}
}
如何访问Ts的集合以返回它们?这可能吗?
感谢您的帮助。
答案 0 :(得分:3)
对于Linq-to-SQL,这应该有效:
public IQueryable<T> GetResultL2S<T>() where T : class {
MyDataContext db = new MyDataContext();
return db.GetTable<T>();
}
或者,如果您使用的是Entity Framework,那么您可以执行以下操作:
public IQueryable<T> GetResultEF<T>() {
YourEntities db = new YourEntities();
return db.CreateQuery<T>(String.Format("[{0}s]", typeof(T).Name));
}
假设您的实体集可以通过添加s来复数。如果情况并非如此,请查看System.Data.Entity.Design.PluralizationServices.PluralizationService