.net MVC5+EF6+bootstrap搭建框架,从入门到精通(一)
一、前言废话
心血来潮把以前用过的知识来个系统的整理,教你一步步熟悉.net MVC希望能给自己和别人带来帮助,关注绝望的zzk,让你的编码人生不再绝望!
创建项目
.net mvc 搭建三层:
- 搭建基本框架 ,搭建DAL BLL Model都是类库 UI选mvc;
- 直接生成实体数据模型 如下图,Model层右键新建实体数据模型;
- DAL层引用Model新增BaseDal,BaseDbContext两个类
BaseDal.cs代码
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace zzkMvc.DAL
{
/// <summary>
/// 负责操作数据库中的所有表的普通增,删,查,改操作的
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class BaseDal<TEntity> where TEntity : class
{
//1.0实例化EF上下文容器对象
BaseDBContext db = new BaseDBContext();
DbSet<TEntity> _dbset;
public BaseDal()
{
//初始化
_dbset = db.Set<TEntity>();
}
#region 查询
public List<TEntity> Query(Expression<Func<TEntity, bool>> where)
{
return _dbset.Where(where).ToList();
}
public List<TEntity> QueryJoin(Expression<Func<TEntity, bool>> where, string[] tableNames)
{
//将子类_dbset 赋值给父类的query
DbQuery<TEntity> query = _dbset;
foreach (var item in tableNames)
{
//遍历要连表的表名称,最终得到所有连表以后的DbQuery对象
query = query.Include(item);
}
return query.Where(where).ToList();
}
#endregion
#region 新增
public void Add(TEntity model)
{
_dbset.Add(model);
}
#endregion
#region 编辑
public void Edit(TEntity model, string[] propertyName)
{
if (model == null)
{
throw new Exception("model必须为实体的对象");
}
if (propertyName == null || propertyName.Any() == false)
{
throw new Exception("必须至少指定一个要修改的属性");
}
//将model追加到EF容器
DbEntityEntry entry = db.Entry(model);
entry.State = EntityState.Unchanged;
foreach (var item in propertyName)
{
entry.Property(item).IsModified = true;
}
}
#endregion
#region 物理删除
//EntityState.Unchanged
public void Delete(TEntity model, bool isAddedEFContext)
{
if (isAddedEFContext == false)
{
_dbset.Attach(model);
}
//修改状态为deleted
_dbset.Remove(model);
}
#endregion
#region 统一执行保存
public int SaveChanges()
{
return db.SaveChanges();
}
#endregion
}
}
BaseDBContext.cs代码
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace zzkMvc.DAL
{
/// <summary>
/// 自定义的EF上下文容器类
/// </summary>
public class BaseDBContext : DbContext
{
/// <summary>
/// 负责根据指定的数据库链接字符串,初始化EF
/// </summary>
//此处name值在Model层的App.config中查找
public BaseDBContext() : base("name=zzkMvcEntities") { }
}
}
新建tb_staffDal继承BaseDal,tb_staffDal.cs代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zzkMvc.Model;
namespace zzkMvc.DAL
{
//此处继承BaseDal
public class tb_staffDa:BaseDal<tb_staff>
{
}
}
- BLL层引用Model、Dal 新建BaseBll.cs初始化BaseDal;
BaseBll.cs代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using zzkMvc.DAL;
namespace zzkMvc.BLL
{
public class BaseBLL<TEntity> where TEntity : class
{
//初始化BaseDal泛型类的对象
BaseDal<TEntity> bdal = new BaseDal<TEntity>();
#region 查询
public List<TEntity> Query(Expression<Func<TEntity, bool>> where)
{
return bdal.Query(where);
}
public List<TEntity> QueryJoin(Expression<Func<TEntity, bool>> where, string[] tableNames)
{
return bdal.QueryJoin(where, tableNames);
}
#endregion
#region 新增
public void Add(TEntity model)
{
bdal.Add(model);
}
#endregion
#region 编辑
/// <summary>
/// 要求:model必须是自己定义的实体,此时没有追加到EF容器中
/// </summary>
/// <param name="model"></param>
public void Edit(TEntity model, string[] propertyName)
{
bdal.Edit(model, propertyName);
}
#endregion
#region 物理删除
/// <summary>
/// model必须是自己定义的,一般是按照主键来删除
/// </summary>
/// <param name="model">要删除的实体对象</param>
/// <param name="isAddedEFContext">true:表示model以及追加到了ef容器,false:未追加</param>
public void Delete(TEntity model, bool isAddedEFContext)
{
bdal.Delete(model, isAddedEFContext);
}
#endregion
#region 统一执行sql语句
public int SaveChanges()
{
return bdal.SaveChanges();
}
#endregion
}
}
新建tb_staffBll.cs继承BaseBll,代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zzkMvc.Model;
namespace zzkMvc.BLL
{
public class tb_staffBll:BaseBLL<tb_staff>
{
}
}
-
安装entityframework工具——nuget包;
-
修改UI层的web.config 打开Model层的App.config找到下图代码复制到UI层的web.config中;
-
至此框架基本搭建完毕,下面开始用.net mvc 写几个页面实现对数据库的增删改查。
新建一个视图页,实现简单的列表查询
新建一个Test()右键添加视图,如下图所示
Test()代码如下:
zzkMvcEntities zzkmvc = new zzkMvcEntities();
tb_staffBll cbll = new tb_staffBll();
//简单的查询
public ActionResult Test()
{
传统Tsql
SqlParameter[] parameters = {
new SqlParameter("@userName", SqlDbType.NVarChar,50),
new SqlParameter("@loginTime", SqlDbType.DateTime),
new SqlParameter("@email", SqlDbType.NVarChar,30),
new SqlParameter("@sex", SqlDbType.Bit,1),
new SqlParameter("@roleid", SqlDbType.TinyInt,1),
new SqlParameter("@groupID", SqlDbType.Int,4),
new SqlParameter("@Remark",SqlDbType.NVarChar,-1)
};
parameters[0].Value = "";
parameters[1].Value = "";
parameters[2].Value = "";
parameters[3].Value = "";
parameters[4].Value = "";
parameters[5].Value = "";
parameters[6].Value = "";
//SqlParameter[] parameters = {
//new SqlParameter("@Name", SqlDbType.NVarChar, 50)
// };
//parameters[0].Value = "张三";
//var model2 = zzkmvc.Database.SqlQuery<tb_staff>("select * from tb_staff where Name=@Name",parameters).ToList();
//return View(model2.ToList());
//linq to entityframwork查询
//var users2 = zzkmvc.tb_staff.Where<tb_staff>(user => user.Name != "ls" || user.Phone != "").ToList();//简单查询&&
//return View(users2);
//复杂l2e
//using (var dbContext = new zzkMvcEntities())
//{
// IQueryable<tb_staff> iqm = dbContext.tb_staff;
// iqm = iqm.Where(user => user.Name != "ls" || user.Phone != "");
// iqm = iqm.Where(user => user.Phone != "ls");
// iqm = iqm.Where(user => user.Nationality != "美国" || user.Salary == 5000.00);
// return View(iqm.ToList());
// //select * from tb_staff where (Name != "ls" || Phone != "") and (Phone != "ls") and (Nationality != "美国" || Salary == "5000.00")
//}
//linq
var user = from r in zzkmvc.tb_staff
where (r.Phone != "ls" && r.Nationality=="美国") || r.Salary==5000.00
select r;
return View(user.ToList());
}
前台页Test.cshtml代码,此页是上一步添加视图生成的
@model IEnumerable<zzkMvc.Model.tb_staff>
@{
ViewBag.Title = "Test";
}
<h2>Test</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Sex)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Phone)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th>
@Html.DisplayNameFor(model => model.Nationality)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sex)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.DisplayFor(modelItem => item.Nationality)
</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>
增、删、改
HomeController.cs后台页增删改相关代码
public ActionResult Add()
{
return View();
}
public ActionResult Edit(int id)
{
var user = cbll.Query(c => c.Id == id).ToList()[0];
return View(user);
}
[HttpPost]
public ActionResult Update()
{
var id = Convert.ToInt32(Request["Id"]);
var userName = Request["Name"];
if (userName != "" && userName != null)
{
var user = cbll.Query(c => c.Id == id).ToList()[0];
//修改
user.Name = userName;
cbll.SaveChanges();
//return View("Index",cbll.Query(c => c.RealName.Contains("张")).ToList());
return Redirect("~/home/Test");
}
return Redirect("~/home/Edit?id=" + id);
}
[HttpPost]
public ActionResult AddEdit()
{
var Name = Request["Name"];
var Sex = Request["Sex"];
var Age = Request["Age"];
var Phone = Request["Phone"];
var Salary = Request["Salary"];
var Nationality = Request["Nationality"];
if (Name != "" && Name != null)
{
//新增测试:
tb_staff model = new tb_staff()
{
Name = Name,
Sex = Convert.ToBoolean(Sex),
Age = Convert.ToInt32(Age),
Phone = Phone,
Salary = (float)Convert.ToDouble(Salary),
Nationality = Nationality
};
cbll.Add(model);
cbll.SaveChanges();
return Redirect("~/home/Test");
}
return Redirect("~/home/Add");
}
public ActionResult Delete(int id)
{
var user = cbll.Query(c => c.Id == id).ToList()[0];
//修改
user.Name = "sansa";
//删除
//cbll.Delete(user, true);//执行sql语句 打开关闭了一次ado.net链接
///
统一将上面的新增,编辑,删除分别生成insert,update,delete语句一次性发送给数据库执行
cbll.SaveChanges();
//return View("Index",cbll.Query(c => c.RealName.Contains("张")).ToList());
return Redirect("~/home/Test");
}
Add、Edit右键添加视图,如下
Add.cshtml、Edit.cshtml,修改一下代码 就可以提交到后台了 ,如下
至此,.net mvc5+EF6+bootstrap三层框架搭建完毕,并实现基本的增删改查,赶紧打开vs开始吧,临渊羡鱼不如退而结网!