开发者

C# Linq-to-SQL Create a Generic Repository

开发者 https://www.devze.com 2023-02-13 04:58 出处:网络
I have a few repositories that all generally look like this public class DepartmentsRepository { private PersonnelActionFormDataContext db = new PersonnelActionFormDataContext();

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>
    开发者_JAVA技巧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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号