我正在尝试使用 LINQ to SQL 数据上下文来实现通用存储库模式。上下文以 NULL 形式出现。为了获得上下文并使其发挥作用,需要进行哪些更改?
我有一个dbml文件,其中包含以下内容:
public partial class LibraryManagementClassesDataContext : System.Data.Linq.DataContext
它有帐户实体
代码
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();
}
}
阅读: