用Entity Framework对数据表进行增删查改
首先打开SQL Server 数据库,创建好数据库,数据表
--建库
create database School
--使用这个数据库
use School
--建表
create table Student(
id int primary key identity(1,1),
Name nvarchar(20),
Age int ,
Address nvarchar(20),
studyData nvarchar(100),
)
--插入测试数据
insert into Student
values('张三',23,'荆州','2005/5/1'),
('江三',23,'南京州','2012/5/1')
接着打开Visual Studio 2017,新建一个ASP.NET Web项目,起名为website
右键解决方案,添加一个类库项目,名为DAL的数据访问层,
右键解决方案,再添加一个类库项目,名为BLL的业务逻辑层,
再右键解决方案,添加一个类库项目,名为Model的模型层,
接着右键模型层,添加新建项,选择ADO.NET实体数据模型。
选择“来自数据库的EF设计器”。点下一步
点击新建连接,来到这一界面,选择你自己的数据库连接方式以及数据库名称,点确定。
点击表左边的箭头,选择你的数据表,点完成。
选择 “是”
一段时间后,vs界面出现了这个数据表。
接下来这一步比较重要,在模型层的引用栏找到Entity Framework这一引用文件,右键,点击在对象浏览器中查看。
复制蓝色区域的路径。
找到视图层,右键视图层的引用,点击添加引用。
点击浏览。
将刚复制的路径粘贴到这一区域。
选择这两个文件,点击添加。
勾上这两个,确定
在DAL层添加一个StudentDAO类。
里面写如增,删,查,改语句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
namespace DAL
{
public class StudentDAO
{
SchoolEntities se = new SchoolEntities();
public IEnumerable<Student> Select()
{
var result = (from student in se.Student select student).ToList();
return result;
}
//添加
public int Add(Student student)
{
se.Student.Add(student);
return se.SaveChanges();
}
//查询指定ID的用户
public Student SelectById(int id)
{
var stu = (from s in se.Student where s.Id == id select s).FirstOrDefault();
return stu;
}
//删除
public int Delete(int id)
{
var stu = (from s in se.Student where s.Id == id select s).FirstOrDefault();
se.Student.Remove(stu);
return se.SaveChanges();
}
//更新
public int Update(Student student)
{
se.Entry<Student>(student).State = System.Data.Entity.EntityState.Modified;
return se.SaveChanges();
}
}
}
在BLL层添加一个StudentService类。
里面调用StudentDAO类中的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using Model;
namespace BLL
{
public class StudentService
{
private StudentDAO dAO = new StudentDAO();
//查询全部
public IEnumerable<Student> Select()
{
return dAO.Select();
}
//根据id查询
public Student SelectById(int id)
{
return dAO.SelectById(id);
}
//添加
public int Add(Student student)
{
return dAO.Add(student);
}
//删除
public int Delete(int id)
{
return dAO.Delete(id);
}
//更新
public int Update(Student student)
{
return dAO.Update(student);
}
}
}
右键视图层,添加一个默认窗体。
在div中添加Grigview控件
点击左下角的设计,点击控件,新建数据源
选择对象,确定
选择这个方法。下一步
选择Select方法。完成
将默认窗体设为起始页,Ctrl+F5运行。结果图