この文書の現在のバージョンと選択したバージョンの差分を表示します。
次のリビジョン | 前のリビジョン | ||
mvc:リポジトリパターン [2022/07/28 10:37] ips 作成 |
— (現在) | ||
---|---|---|---|
ライン 1: | ライン 1: | ||
- | ====== リポジトリパターン ====== | ||
- | <code c# "Program.cs"> | ||
- | var builder = WebApplication.CreateBuilder(args); | ||
- | builder.Services.AddDbContext<MvcMovieContext>(options => | ||
- | options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext") ?? throw new InvalidOperationException("Connection string 'MvcMovieContext' not found."))); | ||
- | |||
- | </code> | ||
- | |||
- | <code c# "Models/Pulish.cs"> | ||
- | namespace MvcMovie.Models | ||
- | { | ||
- | public class Publish | ||
- | { | ||
- | public int Id { get; set; } | ||
- | public string Title { get; set; } | ||
- | } | ||
- | } | ||
- | </code> | ||
- | |||
- | <code c# "Models/IPublishRepository.cs"> | ||
- | using Microsoft.AspNetCore.Mvc; | ||
- | |||
- | namespace MvcMovie.Models | ||
- | { | ||
- | public interface IPublishRepository | ||
- | { | ||
- | Task<List<Publish>> ToListAsync(); | ||
- | } | ||
- | } | ||
- | |||
- | </code> | ||
- | |||
- | <code c# "Models/PubRepository.cs"> | ||
- | using Microsoft.AspNetCore.Mvc; | ||
- | using Microsoft.EntityFrameworkCore; | ||
- | using MvcMovie.Data; | ||
- | |||
- | |||
- | namespace MvcMovie.Models | ||
- | { | ||
- | public class PubRepository : IPublishRepository | ||
- | { | ||
- | private MvcMovieContext _context; | ||
- | |||
- | public PubRepository(MvcMovieContext context) | ||
- | { | ||
- | _context = context; | ||
- | } | ||
- | |||
- | public async Task<List<Publish>> ToListAsync() | ||
- | { | ||
- | return (List<Publish>)await _context.Publish.ToListAsync(); | ||
- | } | ||
- | |||
- | } | ||
- | } | ||
- | </code> | ||
- | |||
- | <code c# "Controllers/pubrepository.cs"> | ||
- | using Microsoft.AspNetCore.Mvc; | ||
- | using Microsoft.EntityFrameworkCore; | ||
- | using Microsoft.EntityFrameworkCore.Infrastructure; | ||
- | using Microsoft.Extensions.Options; | ||
- | using MvcMovie.Data; | ||
- | using MvcMovie.Models; | ||
- | |||
- | namespace MvcMovie.Controllers | ||
- | { | ||
- | public class PublishesController : Controller | ||
- | { | ||
- | |||
- | private IPublishRepository pubrepository; | ||
- | private MvcMovieContext _context; | ||
- | |||
- | public PublishesController(MvcMovieContext context) | ||
- | { | ||
- | pubrepository = new PubRepository(context); | ||
- | } | ||
- | |||
- | public async Task<IActionResult> Index() | ||
- | { | ||
- | return View(await pubrepository.ToListAsync()); | ||
- | } | ||
- | } | ||
- | } | ||
- | </code> |