原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码
上一讲我们创建了一系列的解决方案,我们通过一个例子来看看层与层之间的关系。
我们把Controllers分离出来了BLL层和DAL层
BLL专注于业务上的处理
DAL专注于数据访问层的处理
而Controller跟清楚的与View交互
我们上一讲已经在EF添加了一个实体SysSample
下面我们创建IDAL,DAL,IBLL,BLL的代码吧
using App.Models;
using System.Linq;
namespace App.IDAL
{
public interface ISysSampleRepository
{
/// <summary>
/// 获取列表
/// </summary>
/// <param name="db">数据库上下文</param>
/// <returns>数据列表</returns>
IQueryable<SysSample> GetList(DBContainer db);
/// <summary>
/// 创建一个实体
/// </summary>
/// <param name="entity">实体</param>
int Create(SysSample entity);
/// <summary>
/// 删除一个实体
/// </summary>
/// <param name="entity">主键ID</param>
int Delete(string id); /// <summary>
/// 修改一个实体
/// </summary>
/// <param name="entity">实体</param>
int Edit(SysSample entity);
/// <summary>
/// 获得一个实体
/// </summary>
/// <param name="id">id</param>
/// <returns>实体</returns>
SysSample GetById(string id);
/// <summary>
/// 判断一个实体是否存在
/// </summary>
bool IsExist(string id);
}
}
ISysSampleRepository.cs
using System;
using System.Linq;
using App.IDAL;
using App.Models;
using System.Data; namespace App.DAL
{
public class SysSampleRepository : ISysSampleRepository, IDisposable
{
/// <summary>
/// 获取列表
/// </summary>
/// <param name="db">数据库上下文</param>
/// <returns>数据列表</returns>
public IQueryable<SysSample> GetList(DBContainer db)
{
IQueryable<SysSample> list = db.SysSample.AsQueryable();
return list;
}
/// <summary>
/// 创建一个实体
/// </summary>
/// <param name="db">数据库上下文</param>
/// <param name="entity">实体</param>
public int Create(SysSample entity)
{
using (DBContainer db = new DBContainer())
{
db.SysSample.AddObject(entity);
return db.SaveChanges();
}
}
/// <summary>
/// 删除一个实体
/// </summary>
/// <param name="db">数据库上下文</param>
/// <param name="entity">主键ID</param>
public int Delete(string id)
{
using (DBContainer db = new DBContainer())
{
SysSample entity = db.SysSample.SingleOrDefault(a => a.Id == id);
if (entity != null)
{ db.SysSample.DeleteObject(entity);
}
return db.SaveChanges();
}
} /// <summary>
/// 修改一个实体
/// </summary>
/// <param name="db">数据库上下文</param>
/// <param name="entity">实体</param>
public int Edit(SysSample entity)
{
using (DBContainer db = new DBContainer())
{
db.SysSample.Attach(entity);
db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
return db.SaveChanges();
}
}
/// <summary>
/// 获得一个实体
/// </summary>
/// <param name="id">id</param>
/// <returns>实体</returns>
public SysSample GetById(string id)
{
using (DBContainer db = new DBContainer())
{
return db.SysSample.SingleOrDefault(a => a.Id == id);
}
}
/// <summary>
/// 判断一个实体是否存在
/// </summary>
/// <param name="id">id</param>
/// <returns>是否存在 true or false</returns>
public bool IsExist(string id)
{
using (DBContainer db = new DBContainer())
{
SysSample entity = GetById(id);
if (entity != null)
return true;
return false;
}
}
public void Dispose()
{ }
}
}
SysSampleRepository.cs
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由T4模板自动生成
// 生成时间 2013-03-12 11:19:12 by App
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------ using System.Collections.Generic;
using App.Models; namespace App.IBLL
{ public interface ISysSampleBLL
{
/// <summary>
/// 获取列表
/// </summary>
/// <param name="pager">JQgrid分页</param>
/// <param name="queryStr">搜索条件</param>
/// <returns>列表</returns>
List<SysSample> GetList(string queryStr);
/// <summary>
/// 创建一个实体
/// </summary>
/// <param name="errors">持久的错误信息</param>
/// <param name="model">模型</param>
/// <returns>是否成功</returns>
bool Create(SysSample model);
/// <summary>
/// 删除一个实体
/// </summary>
/// <param name="errors">持久的错误信息</param>
/// <param name="id">id</param>
/// <returns>是否成功</returns>
bool Delete(string id); /// <summary>
/// 修改一个实体
/// </summary>
/// <param name="errors">持久的错误信息</param>
/// <param name="model">模型</param>
/// <returns>是否成功</returns>
bool Edit(SysSample model);
/// <summary>
/// 根据ID获得一个Model实体
/// </summary>
/// <param name="id">id</param>
/// <returns>Model实体</returns>
SysSample GetById(string id);
/// <summary>
/// 判断是否存在实体
/// </summary>
/// <param name="id">主键ID</param>
/// <returns>是否存在</returns>
bool IsExist(string id);
}
}
ISysSampleBLL
using System;
using System.Collections.Generic;
using System.Linq;
using App.Models;
using App.Common;
using App.IBLL;
using App.IDAL;
using App.DAL; namespace App.BLL
{
public class SysSampleBLL :ISysSampleBLL
{
DBContainer db = new DBContainer(); ISysSampleRepository Rep = new SysSampleRepository(); /// <summary>
/// 获取列表
/// </summary>
/// <param name="pager">JQgrid分页</param>
/// <param name="queryStr">搜索条件</param>
/// <returns>列表</returns>
public List<SysSample> GetList(string queryStr)
{ IQueryable<SysSample> queryData =Rep.GetList(db); return queryData.ToList();
} /// <summary>
/// 创建一个实体
/// </summary>
/// <param name="errors">持久的错误信息</param>
/// <param name="model">模型</param>
/// <returns>是否成功</returns>
public bool Create(SysSample entity)
{
try
{
if (Rep.Create(entity) == )
{
return true;
}
else
{ return false;
}
}
catch (Exception ex)
{
//ExceptionHander.WriteException(ex);
return false;
}
}
/// <summary>
/// 删除一个实体
/// </summary>
/// <param name="errors">持久的错误信息</param>
/// <param name="id">id</param>
/// <returns>是否成功</returns>
public bool Delete(string id)
{
try
{
if (Rep.Delete(id) == )
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
//ExceptionHander.WriteException(ex);
return false;
}
} /// <summary>
/// 修改一个实体
/// </summary>
/// <param name="errors">持久的错误信息</param>
/// <param name="model">模型</param>
/// <returns>是否成功</returns>
public bool Edit(SysSample entity)
{
try
{
if (Rep.Edit(entity) == )
{
return true;
}
else
{ return false;
} }
catch (Exception ex)
{ //ExceptionHander.WriteException(ex);
return false;
}
}
/// <summary>
/// 判断是否存在实体
/// </summary>
/// <param name="id">主键ID</param>
/// <returns>是否存在</returns>
public bool IsExists(string id)
{
if (db.SysSample.SingleOrDefault(a => a.Id == id) != null)
{
return true;
}
return false;
}
/// <summary>
/// 根据ID获得一个实体
/// </summary>
/// <param name="id">id</param>
/// <returns>实体</returns>
public SysSample GetById(string id)
{
if (IsExist(id))
{
SysSample entity = Rep.GetById(id); return entity;
}
else
{
return null;
}
} /// <summary>
/// 判断一个实体是否存在
/// </summary>
/// <param name="id">id</param>
/// <returns>是否存在 true or false</returns>
public bool IsExist(string id)
{
return Rep.IsExist(id);
}
}
}
SysSampleBLL
接口是用来集成的,所以BLL:IBLL DAL:IDAL
上面的类注释都很明白明了了。(只是代码很糟糕)
我们创建一个空控制器 SysSample,并添加index视图
@model IEnumerable<App.Models.SysSample> @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Bir)
</th>
<th>
@Html.DisplayNameFor(model => model.Photo)
</th>
<th>
@Html.DisplayNameFor(model => model.Note)
</th>
<th>
@Html.DisplayNameFor(model => model.CreateTime)
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Bir)
</td>
<td>
@Html.DisplayFor(modelItem => item.Photo)
</td>
<td>
@Html.DisplayFor(modelItem => item.Note)
</td>
<td>
@Html.DisplayFor(modelItem => item.CreateTime)
</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>
</body>
</html>
Index.cshtml
打开Home index的第48行修改为<iframe scrolling="auto" frameborder="0" src="/SysSample" style="width: 100%; height: 100%;"></iframe>
我们将在easyui框架预览
运行之后你可能会报错数据库没得连接,因为我们把EF放到了App.Models下,在App.Admin的web.config需要修改connectionStrings
为App.Models下的App.Config的connectionStrings包含节点
编译器错误消息: CS0012: 类型“System.Data.Objects.DataClasses.EntityObject”在未被引用的程序集中定义。
必须添加对程序集 “System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089” 的引用。
打开web.config 查找compilation debug="true" targetFramework="4.5"
添加节点
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
这里给出web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DBContainer" connectionString="metadata=res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=DB;user id=sa;password=zhaoyun123!@#;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings> <appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web> <compilation debug="true" targetFramework="4.5" >
<assemblies> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
web.config
我们往数据库插入几条记录这时你应该看到效果了
BLL DAL的增删改都做好了,大家有兴趣就补充一下下吧,都说破了就不好啦。