標籤

2017年5月26日 星期五

ASP.NET MVC 5 - Adding a Model

᳓前言
本篇文章將"Adding a Model"、"Creating a Connection String and Working with SQL Server LocalDB"與"Accessing Your Model's Data from a Controller"的前半部分合併整理而成,後半部分有一些其他說明,包含Strongly Typed Models以及在Visual Studio中開啟資料表等,有需要的再麻煩去看原文。

᳓重點整理
  • 使用被稱為Entity Framework(簡稱為EF)的.NET Framework資料存取技術,進行Model類別的定義及運作。EF支援Code First的開發模式,能夠經由程式碼建立Model物件。
  • 修改Web.config的connection string以連接LocalDB。(不建議產品化的應用程式仍然使用local database,可以輕鬆整合至SQL Server或SQL Azure)
  • 新增MoviesController.cs,以Controller取得Model資料並透過View顯示在瀏覽器中,且Controller可透過Model進行資料庫的新增、修改、刪除。

᳓實作1. 新增Models/Movie.cs
1. 右鍵Models資料夾 -> Add -> Class
2. 輸入Movie -> Add

᳓實作2. 修改Movie.cs的內容
新增必要的屬性於物件中,每個屬性可視為table中的column(ID、Title、ReleaseDate、Genre、Price),此物件的每筆instance可視為table的每筆資料。接著新增MovieDBContext,其衍生自EF所提供的DbContext基礎類別(需using System.Data.Entity),負責處理取得、儲存及更新Movie的instance於資料庫中。
using System;
using System.Collections.Generic;
using System.Data.Entity; // DbContext
using System.Linq;
using System.Web;
namespace WebApplication1.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
view raw Movie.cs hosted with ❤ by GitHub

᳓實作3. 修改Web.config
新增<connectionStrings>。(connection string的name一定要與DbContext的類別名稱相同,而資料庫的名稱可以自由命名為*.mdf)
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20170525034836.mdf;Initial Catalog=aspnet-WebApplication1-20170525034836;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="MovieDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Movies.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
view raw Web.config hosted with ❤ by GitHub

᳓實作4. 新增Controllers/MoviesController.cs
由於這次選擇的是"MVC 5 Controller with views, using Entity Framework",因此新增完畢後會自行於MoviesController.cs中新增CRUD (Create, Read, Update, and Delete) Action程式碼,並於自動建立Views/Movies的資料夾時 一併建立其頁面Create.cshtml、Delete.cshtml、Details.cshtml、Edit.cshtml、Index.cshtml。若是新增Controller時遇到錯誤,請先重新建置專案。
1. 右鍵Controller資料夾 -> Add -> Controller -> MVC 5 Controller with views, using Entity Framework -> Add
2. 選擇Model class(Movie ({WebApplication}.Models))、Data context class(MovieDBContext ({WebApplication}.Models))並輸入Controller name(MoviesController) -> Add

᳓實作5. 透過瀏覽器新增一筆Movie資料
本篇文章並沒有建立LocalDB的說明,因為當第一次進行資料庫存取的同時便會自動建立LocalDB。
1. 在網址列輸入"http://{localhost:port}/Movies",執行Movies的預設動作(Index) -> Create New
2. 輸入欄位資料(日期格式為月/日/年) -> Create
3. 新增完畢會自動跳回Index頁面,可以看到新增了剛剛所輸入的資料,而其他功能也都可以運作

沒有留言:

張貼留言