0

LINQtoSQLデータコンテキストを使用してジェネリックリポジトリパターンを実装しようとしています。コンテキストは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();
    }

}

読む:

  1. LinqToSqlは、DataContextのベストプラクティスを宣言してインスタンス化しますか?
4

2 に答える 2

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.DataContextしますLibraryManagementClassesDataContext

于 2012-06-20T06:29:24.657 に答える
0

コンテキストはインスタンス化されていないため、クラスコンストラクター内で作成できます。このようなもの...

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

また、コンテキストを短命に保ち、早期に破棄することもできます。早期に破棄する方法の詳細については、こちらをご覧ください:LINQ-SQLでは、DataContextのラップはusingステートメントです-pros cons

public virtual System.Linq.IQueryable<T> GetAll()
{
    using (var context == new System.Data.Linq.DataContext())
    {
        return Context.GetTable<T>();
    }
}
于 2012-06-20T06:28:44.560 に答える