ASP.NET Core MVC+EF Coreプロジェクト実戦

6857 ワード

ASP.NET Core MVC+EF Coreプロジェクト実戦
プロジェクトの背景
本プロジェクトは『Pro Entity Framework Core 2 for ASP.NET Core MVC』の本を参考にして、プロジェクト内容はparty招待回答です.
新規プロジェクト
本プロジェクト開発ツールはVS 2017であり、VS 2017を開き、新規プロジェクトを作成し、ASPを選択する.NETCore Webアプリケーション、プロジェクト名はPartyInvites、OKをクリックし、テンプレートをMVC(手間を省くため)に選択します.もちろんMVCプロセスを熟知するためにも、空のテンプレートを選択して自分でプロジェクト構造を構築することができます.
プロジェクト開発
1.データエンティティクラスの作成とデータベースコンテキストクラスModelsフォルダの下に2つのクラスを作成します.DataContextとGuestResponseクラスです.クラスの内容は以下の通りです.
public class GuestResponse
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool? WillAttend { get; set; }
    }
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {

        }
        public DbSet Responses { get; set; }
    }

2.ControllerとViewを作成してControllersフォルダの下にあるHomeControllerファイルを開きます(空のテンプレートを選択した学生が自分でフォルダとHomeControllerファイルを作成します).HomeControllerの具体的なコードは以下の通りです.
public class HomeController : Controller
    {
        private DataContext _dataContext;
        public HomeController(DataContext dataContext) => _dataContext = dataContext;
        public IActionResult Index() => View();
        public IActionResult Respond() => View();
        [HttpPost]
        public IActionResult Respond(GuestResponse response)
        {
            _dataContext.Responses.Add(response);
            _dataContext.SaveChanges();
            return RedirectToAction(nameof(Thanks),
                    new { Name = response.Name, WillAttend = response.WillAttend });
        }
        public IActionResult Thanks(GuestResponse response)
        {
            return View(response);
        }
        public IActionResult ListResponses() =>
                    View(_dataContext.Responses.OrderByDescending(r => r.WillAttend));
    }

Views/Sharedフォルダの下の_を変更Layout.cshtmlファイル:




    
    Party Invites
    


    
@RenderBody()

ホームフォルダの下でIndexを変更します.cshtml、内容は以下の通りです.

We're going to have an exciting party!

And you are invited

RSVP Now

新しいcshtmlファイルを作成します.cshtml,

@model IEnumerable

Here is the list of people who have responded

@foreach (GuestResponse r in Model) { }
Name Email Phone Attending
@r.Name @r.Email @r.Phone @(r.WillAttend == true ? "Yes" : "No")

Respond.cshtml,
@model GuestResponse

RSVP


Thanks.cshtml
@model GuestResponse

Thank you, @Model.Name!

@if (Model.WillAttend == true) {
It's great that you're coming. The drinks are already in the fridge!
} else {
Sorry to hear that you can't make it, but thanks for letting us know.
} Click here to see who is coming.

EF Coreの設定
データベース接続文字列をappsettingsで構成する.jsonファイルには、次のような内容が追加されています.

    "ConnectionStrings": {
      "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=PartyInvites;Trusted_Connection=True;MultipleActiveResultSets=true"
    }

DefaultConnectionの内容は、自分のデータベース接続文字列です.startupを変更します.csの内容、コードは図のようです
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            //config database connect string
            string conString = Configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext(options =>
            options.UseSqlServer(conString));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            //important
            app.UseMvcWithDefaultRoute();
        }
    }

構成が完了すると、新しいdata Modelに基づいてデータベースを作成しnugetコンソールを開き、コンソールにadd-migrationにadd-migration addDataなどの名前を入力します.実行すると、自動的にmigrationsフォルダが作成され、フォルダにaddDataファイルが作成されます.これは、移行ファイルの作成に成功したことを意味します.次に、update-databaseと入力すると、データベースの作成が完了し、次の表の作成が成功したかどうかをデータベースで確認できます.これでプロジェクトを実行できます.前の段落ではbootstrapが参照されていますが、bootstrapのインストールに成功したかどうか、バージョンの問題に注意する必要があります.そうしないと、ページが正しく表示されない可能性があります.
プロジェクトのソース:https://github.com/zfy1994/Test