一步一步深入 Linq to SQL

本文不是一篇关于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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值