原文:构建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=&quot;data source=.;initial catalog=DB;user id=sa;password=zhaoyun123!@#;MultipleActiveResultSets=True;App=EntityFramework&quot;" 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的增删改都做好了,大家有兴趣就补充一下下吧,都说破了就不好啦。

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码的更多相关文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(1)-前言与目录(持续更新中...)

    转自:http://www.cnblogs.com/ymnets/p/3424309.html 曾几何时我想写一个系列的文章,但是由于工作很忙,一直没有时间更新博客.博客园园龄都1年了,却一直都是空空 ...

  2. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请 系列目录 创建新表单之后,我们就可以起草申请了,申请按照严格的表单步骤和分 ...

  3. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充 系列目录 补充一下,有人要表单的代码,这个用代码生成器生成表Flow_Form表 ...

  4. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支 系列目录 步骤设置完毕之后,就要设置好流转了,比如财务申请大于50000元( ...

  5. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤 系列目录 步骤设计很重要,特别是规则的选择. 我这里分为几个规则 1.按自行 ...

  6. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单 系列目录 设计表单是比较复杂的一步,完成一个表单的设计其实很漫长,主要分为四 ...

  7. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计 系列目录 建立好42节的表之后,每个字段英文表示都是有意义的说明.先建立 ...

  8. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01 工作流在实际应用中还是比较广泛,网络中存在很多工作流的图形化插件,可以做到拉拽的工 ...

  9. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-[过滤器+Cache] 系列目录 上次的探讨没有任何结果,我浏览了大量的文章 ...

  10. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构 本节开始我们要实现工作流,此工作流可以和之前的所有章节脱离关系,也可以紧密合并. 我们当 ...

随机推荐

  1. 单页应用引擎的写法artTemplate

    使用到了ba-haschange.js <script src="../style/js/plugin/template-native-debug.js"></s ...

  2. C#.Net网页加载等待效果漂亮并且简单

    最近网页加载数据比较多,点击后给用户就是白板很不友好,想了很久找了些资料,在网页加载中显示等待画面给客户,页面加载完成自动隐藏等待效果. 在网页后台cs代码:    protected void Pa ...

  3. Struts面试笔记

    Struts2面试题1.struts2工作流程Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher.业务控制器Action和用户实现的企业业务逻辑组件. 核心控制器 ...

  4. CSS and JavaScript Bundling and Minification in ASP.NET 4.5

    ASP.NET 4.5 includes a new feature to minify and bundle CSS and JavaScript within your web applicati ...

  5. 批处理协同blat自动发邮件

    Blat - A Windows (32 & 64 bit) command line SMTP mailer. Use it to automatically eMail logs, the ...

  6. WPF 自定义路由事件

    如何:创建自定义路由事件 首先自定义事件支持事件路由,需要使用 RegisterRoutedEvent 方法注册 RoutedEvent C#语法 public static RoutedEvent ...

  7. u-boot Makefile Source Test

    一.概述 笔者已经写了一篇实现目标文件与源码分开的makefile测试实验,但是觉得不够完美,没有更多的体现u-boot Makefile的工作原理和特点.所以,决定重新修订,使之更加充分的接近u-b ...

  8. JSP中两种模式的总结

    运用JSP/Servlet实现的Web动态交互,主要采用: 模式一:JSP+JavaBean 链接:http://wxmimperio.coding.io/?p=155 模式二;JSP+Servlet ...

  9. 总结Web应用中基于浏览器的安全漏洞

    ‍‍‍‍‍1.浏览器缓存 每次打开一个网站,网页的内容会缓存到用户的机器中.如果这些内容在其他网页中需要重新加载,浏览器加载的是缓存,而不是再次下载内容.如果一些Web应用商店以及显示用户敏感信息(比 ...

  10. jquery deferred

    http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html http:// ...