在LINQ to SQL存储库中设置上下文

时间:2012-06-20 06:25:14

标签: c# .net linq linq-to-sql repository-pattern

我正在尝试使用LINQ to SQL数据上下文实现通用存储库模式。上下文为NULL。为了获得上下文并使其工作,需要做哪些改变?

我有一个 dbml 文件,其中包含以下内容:

public partial class LibraryManagementClassesDataContext : System.Data.Linq.DataContext

它有帐户实体

CODE

static void Main(string[] args)
{

        RepositoryLayer.Repository<RepositoryLayer.Account> selectedRepository = new RepositoryLayer.Repository<RepositoryLayer.Account>();
        AccountBusiness accountBl = new AccountBusiness(selectedRepository);
        List<RepositoryLayer.Account> accountList =   accountBl.GetAllAccounts();

}


namespace RepositoryLayer
{
public interface IRepository<T> where T : class
{
    System.Linq.IQueryable<T> GetAll();
}

public class Repository<T> : IRepository<T> where T : class
{
    public System.Data.Linq.DataContext Context
    {
        get;
        set;
    }

    public virtual System.Linq.IQueryable<T> GetAll()
    {
        if (Context == null)
        {
            throw new Exception("Context is null");
        }
        return Context.GetTable<T>();
    }

}
}

public class AccountBusiness
{
    //IRepository<T>
    RepositoryLayer.IRepository<RepositoryLayer.Account> accountRepository;
    public AccountBusiness(RepositoryLayer.IRepository<RepositoryLayer.Account> repo)
    {
        accountRepository = repo;
    }

    public List<RepositoryLayer.Account> GetAllAccounts()
    {
        IQueryable<RepositoryLayer.Account> acc = accountRepository.GetAll();
        return acc.ToList();
    }

}

读:

  1. LinqToSql declare and instantiate DataContext best practice?

2 个答案:

答案 0 :(得分:1)

当然它是null:你永远不会为你的Context属性赋值。就这么做:

using(var context = new LibraryManagementClassesDataContext())
{
    RepositoryLayer.Repository<RepositoryLayer.Account> selectedRepository = new RepositoryLayer.Repository<RepositoryLayer.Account>();
    selectedRepository.Context = context;
    AccountBusiness accountBl = new AccountBusiness(selectedRepository);
    List<RepositoryLayer.Account> accountList =   accountBl.GetAllAccounts();
}

我还建议Repository.DataContextLibraryManagementClassesDataContext类型。

答案 1 :(得分:0)

由于尚未实例化上下文,您可以在类构造函数中创建它。像这样......

public class Repository<T> : IRepository<T> where T : class
{
    public Repository()
    {
        this.Context = new System.Data.Linq.DataContext()
    }
}

您还可以保持您的上下文短暂存在并尽早处理它。阅读更多关于在此处早期处理它的信息:In LINQ-SQL, wrap the DataContext is an using statement - pros cons

public virtual System.Linq.IQueryable<T> GetAll()
{
    using (var context == new System.Data.Linq.DataContext())
    {
        return Context.GetTable<T>();
    }
}