简体   繁体   English

C#Linq-to-SQL创建通用存储库

[英]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? 如何访问Ts的集合以返回它们? Is this possible? 这可能吗?

Thanks for the help. 谢谢您的帮助。

For Linq-to-SQL this should work: 对于Linq-to-SQL,这应该工作:

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: 或者,如果您使用的是Entity Framework,那么您可以执行以下操作:

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. 这假设您的实体集可以通过添加s来复数。 If that's not the case, then check out System.Data.Entity.Design.PluralizationServices.PluralizationService 如果不是这样,那么请查看System.Data.Entity.Design.PluralizationServices.PluralizationService

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM