一步一步深入 Linq to SQL

来源:互联网 发布:最尴尬的事情 知乎 编辑:程序博客网 时间:2024/06/05 07:58

本文不是一篇关于Linq to SQL的大百科,写本文的目的是引导大家快速上手Linq to SQL。

(一)创建一个数据库test,新建一张表Student,里面有三个字段,分别是:ID、Name、Address。


(二)在vs中新建一个项目LinqtoSql


(三)在项目中添加Linq to SQL类LinqToSql




(四)在服务器资源管理器中选择“添加连接”,将刚刚创建的test数据库加进来,将需要的表拖到.dbml中



(五)接下来就是对student表的增删改查了,在这里我们只展示前台的列表页面、添加页面以及增删改查的所有后台代码


前端展示列表代码如下:

@model IEnumerable<LinqtoSql.ORM.Student>           @{    ViewBag.Title = "Index";}<h2>学生列表</h2><table border="1" width="100%" style="text-align:center;border-collapse:collapse"><tr> <th>编号</th> <th>姓名</th> <th>地址</th> </tr> @foreach (var item in Model){ <tr> <td>@item.ID</td> <td>@item.Name</td> <td>@item.Address</td> </tr> }</table> 


前端添加代码如下:

@{    ViewBag.Title = "Add";} @using (Html.BeginForm("Add", "Student", FormMethod.Post, new { enctype = "multipart/form-data" })) {    <h2>添加学生</h2>    <span>姓名:</span><input type="text" name="Name" />    <span>地址:</span><input type="text" name="Address" />    <input type="submit"  value="提交" /> }


后台代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Data.Linq;using LinqtoSql.ORM;namespace LinqtoSql.Controllers.Student{    public class StudentController : Controller    {        LinqToSqlDataContext lqdc = new LinqToSqlDataContext();               public ActionResult Index()        {            var ilistStudent = from s in lqdc.Student select s;            return View(ilistStudent);        }        [HttpPost]        public ActionResult Add(FormCollection form)        {            ORM.Student student = new ORM.Student();            student.Name = form["Name"].Trim();            student.Address = form["Address"].Trim();            lqdc.Student.InsertOnSubmit(student);            lqdc.SubmitChanges();            return View();        }        public ActionResult Delete()        {            lqdc.Student.DeleteOnSubmit(lqdc.Student.Single(s => s.ID == 1));            lqdc.SubmitChanges();            return View();        }        public ActionResult Update()        {             ORM.Student student =lqdc.Student.Single(c=>c.Name=="王伯仙");            student.Name = "白云";            lqdc.SubmitChanges();            return View();        }        public ActionResult Add()        {            return View();        }    }}





0 0
原创粉丝点击