新增專案實現留言板功能,瞭解MVC的運行機制
1,新增專案
2,添加數據庫文件message.mdf
Ctrl+W,L 打開資料庫連接,添加存放留言的Atricle表
添加字段,後點擊"更新"後看到新增的Atricle表(Content 應該設置為text)
3,添加ADO.NET實體數據模型 (MVC通過實體數據模型對數據庫中的數據進行增删改查)
ADO.NET實體數據模型添加完成。
4,建立Service
我們把對Model中message.mdf數據處理的類單獨放在Service文件夾中,這樣更加方便之後的維護同樣也符合MVC耦合度低的特點,這一步是為Controller中的Action方法做準備。新建Service文件夾,添加messageDBService.cs類(Entity實體和Controller的橋樑):
Service類中添加兩個方法,分別實現對數據的讀和寫
- GetData():讀取並返回數據庫中Article中的數據
- DBCreate():把接收的數據存放到Article表中
using System; using System.Collections.Generic; using System.Linq; using System.Web; using MvcApplication1.Models; //引用Model命名空間 namespace MvcApplication1.Service { public class messageDBService { //實例化實體數據 public Models.messageEntities db=new Models.messageEntities(); //讀取並返回messageEntity中的數據 public List<Article> GetData() { return (db.Article.ToList()); } //把從User接受的數據寫入messageEnitity public void DBCreate(string strTitle,string strContent) { //實例化Artile對象 Article newData=new Article(); //給Artile對象的屬性賦值 newData.Title=strTitle; newData.Content=strContent; newData.time=DateTime.Now; //實體添加到Entity中 db.Article.Add(newData); //保存到數據庫 db.SaveChanges(); } } }