今天教大家如何利用ADO.Net 或者linq实现数据增删改查,新建一个项目
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Linq.Mapping;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class MovieController : Controller
{
MoviesEntities1 _db = new MoviesEntities1();
public ActionResult Index()
{
ViewData.Model = new MoviesEntities1().Movies.ToList();
return View();
}
public ActionResult Details( int id)
{
var model = new MoviesEntities1().Movies.First(m => m.ID == id);
return View(model);
}
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Models.Movie m)
{
try
{
_db.AddToMovies(m);
if ( string.IsNullOrEmpty(m.Movie_Name))
{
ModelState.AddModelError( "Movie_Name", "电影名称不能为空!");
}
if (m.Realease_Date == null)
{
ModelState.AddModelError( "Realease_Date", "放映时间不能为空");
}
foreach (Movie mv in _db.Movies)
{
if (mv.ID == m.ID)
{
ModelState.AddModelError( "ID", "数据库中已经存在Id为" + m.ID + "的数据");
break;
}
}
if (ModelState.IsValid)
{
_db.SaveChanges();
return RedirectToAction( "Index");
}
return View(m);
}
catch
{
return View();
}
}
public ActionResult Edit( int id)
{
var movieToUpdate = _db.Movies.First(m => m.ID == id);
ViewData.Model = movieToUpdate;
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(FormCollection form)
{
var id = Int32.Parse(form[ "id"]);
var movieToUpdate = _db.Movies.First(m => m.ID == id);
TryUpdateModel(movieToUpdate, new string[] { "Movie_Name", "Realease_Date" }, form.ToValueProvider());
if (String.IsNullOrEmpty(movieToUpdate.Movie_Name))
ModelState.AddModelError( "Movie_Name", "Movie_Name is required!");
if (movieToUpdate.Realease_Date == null)
ModelState.AddModelError( "Realease_Date", "Realease_Date is required!");
if (ModelState.IsValid)
{
_db.SaveChanges();
return RedirectToAction( "Index");
}
return View(movieToUpdate);
}
//public ActionResult Delete(int id)
//{
// try
// {
// Models.Movie movie = _db.Movies.First(m => m.ID == id);
// _db.DeleteObject(movie);
// _db.SaveChanges();
// return RedirectToAction("Index");
// }
// catch
// {
// return View("Index");
// }
//}
/// <summary>
/// 使用linq
/// </summary>
/// <returns></returns>
public ActionResult ShowDB()
{
string str = System.Configuration.ConfigurationManager.ConnectionStrings[ "MoviesConnectionString"].ToString();
DataContext MyDataSource = new DataContext(str);
Table<Movies> tb = MyDataSource.GetTable<Movies>();
IQueryable<Movies> MyQuery = from movies in tb where movies.ID >= 5 select movies;
return View(MyQuery);
}
public ActionResult Delete( int id)
{
DataClasses1DataContext DataC1Context = new DataClasses1DataContext();
Movy mv = DataC1Context.Movies.First(c => c.ID == id);
DataC1Context.Movies.DeleteOnSubmit(mv);
DataC1Context.SubmitChanges();
return RedirectToRoute( "start");
}
}
[Table(Name = "Movies")]
public class Movies
{
private int _ID;
private string _Movie_Name;
private DateTime _Realease_Date;
[Column(Storage = "_ID",
AutoSync = AutoSync.OnInsert,
DbType = "int not null indentity",
IsPrimaryKey = true,
IsDbGenerated = true)
]
public int ID
{
set { _ID = ID; }
get { return this._ID; }
}
[Column(Storage = "_Movie_Name",
AutoSync = AutoSync.Always,
DbType = "varchar(200) not null",
IsDbGenerated = true
)]
public string Movie_Name
{
set { _Movie_Name = Movie_Name; }
get { return this._Movie_Name; }
}
[Column(Storage = "_Realease_Date",
AutoSync = AutoSync.Always,
DbType = "datetime not null",
IsDbGenerated = true
)]
public DateTime Realease_Date
{
set { _Realease_Date = Realease_Date; }
get { return _Realease_Date; }
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Linq.Mapping;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class MovieController : Controller
{
MoviesEntities1 _db = new MoviesEntities1();
public ActionResult Index()
{
ViewData.Model = new MoviesEntities1().Movies.ToList();
return View();
}
public ActionResult Details( int id)
{
var model = new MoviesEntities1().Movies.First(m => m.ID == id);
return View(model);
}
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Models.Movie m)
{
try
{
_db.AddToMovies(m);
if ( string.IsNullOrEmpty(m.Movie_Name))
{
ModelState.AddModelError( "Movie_Name", "电影名称不能为空!");
}
if (m.Realease_Date == null)
{
ModelState.AddModelError( "Realease_Date", "放映时间不能为空");
}
foreach (Movie mv in _db.Movies)
{
if (mv.ID == m.ID)
{
ModelState.AddModelError( "ID", "数据库中已经存在Id为" + m.ID + "的数据");
break;
}
}
if (ModelState.IsValid)
{
_db.SaveChanges();
return RedirectToAction( "Index");
}
return View(m);
}
catch
{
return View();
}
}
public ActionResult Edit( int id)
{
var movieToUpdate = _db.Movies.First(m => m.ID == id);
ViewData.Model = movieToUpdate;
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(FormCollection form)
{
var id = Int32.Parse(form[ "id"]);
var movieToUpdate = _db.Movies.First(m => m.ID == id);
TryUpdateModel(movieToUpdate, new string[] { "Movie_Name", "Realease_Date" }, form.ToValueProvider());
if (String.IsNullOrEmpty(movieToUpdate.Movie_Name))
ModelState.AddModelError( "Movie_Name", "Movie_Name is required!");
if (movieToUpdate.Realease_Date == null)
ModelState.AddModelError( "Realease_Date", "Realease_Date is required!");
if (ModelState.IsValid)
{
_db.SaveChanges();
return RedirectToAction( "Index");
}
return View(movieToUpdate);
}
//public ActionResult Delete(int id)
//{
// try
// {
// Models.Movie movie = _db.Movies.First(m => m.ID == id);
// _db.DeleteObject(movie);
// _db.SaveChanges();
// return RedirectToAction("Index");
// }
// catch
// {
// return View("Index");
// }
//}
/// <summary>
/// 使用linq
/// </summary>
/// <returns></returns>
public ActionResult ShowDB()
{
string str = System.Configuration.ConfigurationManager.ConnectionStrings[ "MoviesConnectionString"].ToString();
DataContext MyDataSource = new DataContext(str);
Table<Movies> tb = MyDataSource.GetTable<Movies>();
IQueryable<Movies> MyQuery = from movies in tb where movies.ID >= 5 select movies;
return View(MyQuery);
}
public ActionResult Delete( int id)
{
DataClasses1DataContext DataC1Context = new DataClasses1DataContext();
Movy mv = DataC1Context.Movies.First(c => c.ID == id);
DataC1Context.Movies.DeleteOnSubmit(mv);
DataC1Context.SubmitChanges();
return RedirectToRoute( "start");
}
}
[Table(Name = "Movies")]
public class Movies
{
private int _ID;
private string _Movie_Name;
private DateTime _Realease_Date;
[Column(Storage = "_ID",
AutoSync = AutoSync.OnInsert,
DbType = "int not null indentity",
IsPrimaryKey = true,
IsDbGenerated = true)
]
public int ID
{
set { _ID = ID; }
get { return this._ID; }
}
[Column(Storage = "_Movie_Name",
AutoSync = AutoSync.Always,
DbType = "varchar(200) not null",
IsDbGenerated = true
)]
public string Movie_Name
{
set { _Movie_Name = Movie_Name; }
get { return this._Movie_Name; }
}
[Column(Storage = "_Realease_Date",
AutoSync = AutoSync.Always,
DbType = "datetime not null",
IsDbGenerated = true
)]
public DateTime Realease_Date
{
set { _Realease_Date = Realease_Date; }
get { return _Realease_Date; }
}
}
}
上述代码咋一看去很郁闷。其实和日常的webForm是一样的。首先在Index上单击右键Create一个View,那么这个action方法Index对应的页面就是你所建的View。ViewData.Model = new MoviesEntities1().Movies.ToList();将一个List数据泛型返回给ViewData。ViewData作用类似于ViewState,只能在特定的一个视图使用。而TempData作用类似于session。但是其在controller中只能传递使用一次,之后就会被销毁。所以上述代码就是向视图页面Index.aspx页面发送一组数据。
<%@ Page Title=
"" Language="C#
" MasterPageFile="~/Views/Shared/Site.Master
" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Movie>>" %>
<asp:Content ID= "Content1" ContentPlaceHolderID= "TitleContent" runat= "server">
Index
</asp:Content>
<asp:Content ID= "Content2" ContentPlaceHolderID= "MainContent" runat= "server">
<h2>
Index</h2>
<table>
<tr>
<th>
</th>
<th>
ID
</th>
<th>
Movie_Name
</th>
<th>
Realease_Date
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.ID %>
</td>
<td>
<%: item.Movie_Name %>
</td>
<td>
<%: String.Format( "{0:g}", item.Realease_Date) %>
</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>
<% } %>
</table>
<p>
<%: Html.ActionLink( "Create New", "Create") %>
<%: Html.ActionLink( "跳转到筛选的页面", "ShowDB")%>
</p>
</asp:Content>
<asp:Content ID= "Content1" ContentPlaceHolderID= "TitleContent" runat= "server">
Index
</asp:Content>
<asp:Content ID= "Content2" ContentPlaceHolderID= "MainContent" runat= "server">
<h2>
Index</h2>
<table>
<tr>
<th>
</th>
<th>
ID
</th>
<th>
Movie_Name
</th>
<th>
Realease_Date
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.ID %>
</td>
<td>
<%: item.Movie_Name %>
</td>
<td>
<%: String.Format( "{0:g}", item.Realease_Date) %>
</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>
<% } %>
</table>
<p>
<%: Html.ActionLink( "Create New", "Create") %>
<%: Html.ActionLink( "跳转到筛选的页面", "ShowDB")%>
</p>
</asp:Content>
在这个Html页面,当接收到传过来的数据的时候进行循环遍历,采用HtmlHelper扩展类进行显示。 <%: Html.ActionLink("跳转到筛选的页面", "ShowDB")%>这句的意思是一个超链接,连接到ShowDB这个Action。showDB再调用return view跳转到ShowDb.aspx。
public ActionResult Create()
{
return View();
}
{
return View();
}
[HttpPost]
public ActionResult Create(Models.Movie m){
public ActionResult Create(Models.Movie m){
}
这段代码一个是post方式,另一个是get方式,所谓Get方式即xxx.aspx?id=xx。所以第一个Create所做的动作就是当你点击添加的时候,出现一个添加页面(Create.aspx)而已,仅此而已。第二个post方式的Create才是真正的添加,首先你做个简单的验证。如果验证通过。则调用_db.SaveChanges();在这里需要说明的是Models.Movie m参数的值自动从添加页面可以自动获取。无需写任何代码。对于修改比较特殊,主键不用显示页面view如下
<
%@ Page
Title
="" Language="C#"
MasterPageFile
="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.Movie
>" %>
< asp:Content ID ="Content1" ContentPlaceHolderID ="TitleContent" runat ="server" >
Edit
</asp:Content>
< asp:Content ID ="Content2" ContentPlaceHolderID ="MainContent" runat ="server" >
< h2 >
Edit </h2>
<% using (Html.BeginForm())
{%>
< %: Html.ValidationSummary(true) % >
< fieldset >
< legend >Fields </legend>
< div >
< %: Html.HiddenFor(model = > model.ID)%>
</div>
< div class ="editor-label" >
< %: Html.LabelFor(model = > model.Movie_Name) %>
</div>
< div class ="editor-field" >
< %: Html.TextBoxFor(model = > model.Movie_Name) %>
< %: Html.ValidationMessageFor(model = > model.Movie_Name) %>
</div>
< div class ="editor-label" >
< %: Html.LabelFor(model = > model.Realease_Date) %>
</div>
< div class ="editor-field" >
< %: Html.TextBoxFor(model = > model.Realease_Date, String.Format("{0:g}", Model.Realease_Date)) %>
< %: Html.ValidationMessageFor(model = > model.Realease_Date) %>
</div>
< p >
< input type ="submit" value ="保存" />
</p>
</fieldset>
< % } % >
< div >
< %: Html.ActionLink("返回", "Index") % >
</div>
</asp:Content>
< asp:Content ID ="Content1" ContentPlaceHolderID ="TitleContent" runat ="server" >
Edit
</asp:Content>
< asp:Content ID ="Content2" ContentPlaceHolderID ="MainContent" runat ="server" >
< h2 >
Edit </h2>
<% using (Html.BeginForm())
{%>
< %: Html.ValidationSummary(true) % >
< fieldset >
< legend >Fields </legend>
< div >
< %: Html.HiddenFor(model = > model.ID)%>
</div>
< div class ="editor-label" >
< %: Html.LabelFor(model = > model.Movie_Name) %>
</div>
< div class ="editor-field" >
< %: Html.TextBoxFor(model = > model.Movie_Name) %>
< %: Html.ValidationMessageFor(model = > model.Movie_Name) %>
</div>
< div class ="editor-label" >
< %: Html.LabelFor(model = > model.Realease_Date) %>
</div>
< div class ="editor-field" >
< %: Html.TextBoxFor(model = > model.Realease_Date, String.Format("{0:g}", Model.Realease_Date)) %>
< %: Html.ValidationMessageFor(model = > model.Realease_Date) %>
</div>
< p >
< input type ="submit" value ="保存" />
</p>
</fieldset>
< % } % >
< div >
< %: Html.ActionLink("返回", "Index") % >
</div>
</asp:Content>
本文转自 BruceAndLee 51CTO博客,原文链接:http://blog.51cto.com/leelei/318427,如需转载请自行联系原作者