1

すべてのクエリがコントローラーにならないように、ラッパー クラスを作成したいと考えています。現在、select クエリは Controller に配置されています。しかし、抽象化のために別のレイヤーを作成したいと思います。

私はすでにビューモデルクラスを作成しました。しかし、ラッパークラスは別のものです。

それ、どうやったら出来るの?

4

1 に答える 1

2

コントローラーで直接クエリを実行することはありません。コントローラーが呼び出すサービスレイヤーがあり、各サービスレイヤーはリポジトリを呼び出して、データを挿入、更新、または削除したり、データを戻したりします。

以下のサンプル コードでは、 と を使用ASP.NET MVC3してEntity Framework code firstいます。すべての国を元に戻し、コントローラー/ビューで何らかの理由でそれを使用するとします。

私のデータベースコンテキストクラス:

public class DatabaseContext : DbContext
{
     public DbSet<Country> Countries { get; set; }
}

私の国のリポジトリクラス:

public class CountryRepository : ICountryRepository
{
     DatabaseContext db = new DatabaseContext();

     public IEnumerable<Country> GetAll()
     {
          return db.Countries;
     }
}

私のリポジトリを呼び出す私のサービス層:

public class CountryService : ICountryService
{
     private readonly ICountryRepository countryRepository;

     public CountryService(ICountryRepository countryRepository)
     {
          // Check for nulls on countryRepository

          this.countryRepository = countryRepository;
     }

     public IEnumerable<Country> GetAll()
     {
          // Do whatever else needs to be done

          return countryRepository.GetAll();
     }
}

私のサービスレイヤーを呼び出すコントローラー:

public class CountryController : Controller
{
     private readonly ICountryService countryService;

     public CountryController(ICountryService countryService)
     {
          // Check for nulls on countryService

          this.countryService = countryService;
     }

     public ActionResult List()
     {
          // Get all the countries
          IEnumerable<Country> countries = countryService.GetAll();

          // Do whatever you need to do

          return View();
     }
}

インターネット上には、データの取得方法、表示方法、挿入方法、編集方法などに関する情報がたくさんあります。彼らのチュートリアルに取り組んでください。ではごきげんよう。

于 2012-06-14T12:49:05.977 に答える