(1)建立ASP.NET MVC3 Application-->選擇Internet Application 模版。 (需要.NET Framework 4.0, 並安裝Visual Studio 2010)
(2)在Model目錄下添加類Movie.cs。 包含Movie Model和 Movie DbContext 兩個類。(需要使用Entity Framework,該架構套件含在vs 2010中) 代碼如下
namespace MVC3_Application.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; } }}
(3)右鍵點擊Controller目錄-->添加MovieController類 (要求安裝了SQL Server Compact (MS的一種免費嵌入式資料庫))
選擇參數如下:
添加成功後,
多了一個Controller, MovieController.cs. (裡面有 CRUD方法)
Views目錄下多了名為Movie的目錄,下有5個cshtml檔案。 是Movie的CRUD操作介面。
現在,這些功能就可完備運行。
各命名空間總結如下:
DbContext EntityFramework.dll, v4.0.30319 DbSet EntityFramework.dll, v4.0.30319
2、 理解MVC添加的代碼
MoviesControl.cs
private MovieDBContext db = new MovieDBContext(); // GET: /Movies/ public ViewResult Index() { return View(db.Movies.ToList()); }
The following line from the MoviesController class instantiates a movie database context, as described previously. You can use the movie database context to query, edit, and delete movies.
privateMovieDBContext db =newMovieDBContext();
View/Movies/index.cshtml
@model IEnumerable<MVC3_Application.Models.Movie>
By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. When you created the movie controller, Visual Web Developer automatically included the following @model statement at the top of the Index.cshtml file:
Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item object in the loop is typed as Movie. Among other benefits, this means that you get compile-time checking of the code and full IntelliSense support in the code editor:
@foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.DisplayFor(modelItem => item.ReleaseDate) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.ID }) | @Html.ActionLink("Details", "Details", new { id=item.ID }) | @Html.ActionLink("Delete", "Delete", new { id=item.ID }) </td> </tr> }
3、運行之後,在App_Data目錄下自動產生了 Movies.sdf, 資料庫檔案
Entity Framework Code First detected that the database connection string that was provided pointed to a Movies database that didn’t exist yet, so Code First created the database automatically. You can verify that it's been created by looking in the App_Data folder. If you don't see the Movies.sdf file, click the Show All Files button in the Solution Explorer toolbar, click the Refresh button, and then expand the App_Data folder.
二、字元和byte[]的相互轉換
byte[] byteArray = System.Text.Encoding.Default.GetBytes( str ); 怎麼樣,夠簡單吧? 反過來也是一樣,把byte[]轉成string:string str = System.Text.Encoding.Default.GetString( byteArray );