Code first创建数据库参考这篇文章:EntityFramework-Code-First-数据建模
这次咱们使用database first来引用数据库,生成模型类。如下:
1、右键MVC项目的Models文件夹添加新建项,添加一个ADO.NET实体数据模型
2、选择来自数据库的EF设计器,如下图:
3、新建连接,如下图:
4、Windows和SQLserver身份验证都可以的,这里使用SQLserver身份验证如下图:
5、如下图:
6、选中表(表下面的务必都要勾选上),如下图:
好啦,数据库搞定啦,咱们正式开始操作数据库吧
一、添加数据:
View
@model CRUD.Models.tb1_Student
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Add</title>
</head>
<body>
<div>
@using (Html.BeginForm("Add", "Home", FormMethod.Post))
{
<fieldset>
<legend>添加</legend>
<p>姓 名: @Html.TextBoxFor(x => x.Name)</p>
<p>出生日期: @Html.TextBoxFor(x => x.Birthday)</p>
<p>班级:@Html.DropDownListFor(x => x.tb1_Class.Id, (SelectList)ViewData["drops"])</p> <!--下拉框-->
<input type="submit" value="添加" />
</fieldset>
}
</div>
</body>
</html>
Controller
/// <summary>
public ActionResult Add()
{
var Drops = (from c in db.tb1_Class select c).ToList();
ViewData["drops"] = new SelectList(Drops, "Id", "Name", Drops);//加载下拉框值ID,Name
return View();
}
/// 添加数据
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult Add(tb1_Student stu)
{
tb1_Student stus = new tb1_Student()
{
Name = stu.Name,
Birthday = stu.Birthday,
ClassId = stu.ClassId
};
db.tb1_Student.Add(stus);
int i = db.SaveChanges();
if (i>0)//添加成功
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
二、显示和删除数据:
View
@model CRUD.Models.ClassAndStudent
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.11.0.min.js"></script>
</head>
<body>
@Html.ActionLink("添加", "Add", "Home")
<div>
<table border="1">
<tr>
<th>编号</th>
<th>姓名</th>
<th>班级</th>
<th>出生日期</th>
<th>操作</th>
</tr>
@foreach (CRUD.Models.ClassAndStudent item in ViewBag.list)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Names</td>
<td>@item.Birthday</td>
<td><a href="#" onclick=javascript:if(confirm('确定删除吗?')){deletes(@item.Id)}>删除</a></td>
</tr>
}
</table>
</div>
<script type="text/javascript">
function deletes(id) {//删除
alert(id)
$.ajax({
url: '/Home/GetDelete',
type: "POST",
data: {
id: id
},
success: function (msg) {
if (msg == "1") {
alert("删除成功!");
window.location.href = "Index";
} else{
alert("删除失败!");
}
}
})
}
</script>
</body>
</html>
Controller
/// <summary>
/// 显示
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
var list = (from c in db.tb1_Class join s in db.tb1_Student on c.Id equals s.ClassId select new ClassAndStudent { Names = c.Name, Id = s.Id, Name = s.Name, Birthday = s.Birthday }).ToList();
ViewBag.list = list;
return View();
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpPost]
public int GetDelete(string id)
{
var stu = db.tb1_Student.Find(int.Parse(id));
db.tb1_Student.Remove(stu);
return db.SaveChanges();
}