Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq-to-SQL Create a Generic Repository

I have a few repositories that all generally look like this

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);
    }

I'd like to have some sort of generic base class that could save me some typing, so I started here

 public class GenericRepository<T>
{
    private PersonnelActionFormDataContext db = new PersonnelActionFormDataContext();

    public IQueryable<T> GetAll()
    {
        return db.
    }
}

how do I access the collection of Ts to return them? Is this possible?

Thanks for the help.

like image 315
jim Avatar asked Feb 23 '11 20:02

jim


1 Answers

For Linq-to-SQL this should work:

public IQueryable<T> GetResultL2S<T>() where T : class {
    MyDataContext db = new MyDataContext();
    return db.GetTable<T>();
}

Or, if you're using Entity Framework, then you'd do something like:

public IQueryable<T> GetResultEF<T>() {
    YourEntities db = new YourEntities();
    return db.CreateQuery<T>(String.Format("[{0}s]", typeof(T).Name));
}

That assumes your entity sets can be pluralized by tacking an s on. If that's not the case, then check out System.Data.Entity.Design.PluralizationServices.PluralizationService

like image 198
Adam Rackis Avatar answered Sep 30 '22 01:09

Adam Rackis