EF上下文管理
1.一次请求过来与数据库交互一次。每次操作表都using() 性能差(可以随时释放)
2.N 次操作共用一个DbContext 性能可想而知
3.Web:一个请求共用一个上下文实例
4.WinForm:用using()
实例:
public static MyDbContext GetCurrentDbContext()
{
MyDbContext dbcontext = HttpContext.Current.Items["MyDbContext"] as MyDbContext;
//当前Http上下文不存在当前对象
if (dbcontext == null)
{
dbcontext = new MyDbContext();
HttpContext.Current.Items.Add("", dbcontext);
}
return dbcontext;
}
调用:
protected void Page_Load(object sender, EventArgs e)
{
var dbCotnext = DbContextHelper.GetCurrentDbContext();
}
CallContext 是类似于方法调用的线程本地存储区的专用集合对象,并提供对每个逻辑执行线程都唯一的数据槽。
数据槽不在其他逻辑线程上的调用上下文之间共享。 当 CallContext 沿执行代码路径往返传播并且由该路径中的各个对象检查时,可将对象添加到其中。
//一个线程共用一个上下文实例。一次请求就用一个线程。
MyDbContext dbContext = CallContext.GetData("DbContext") as MyDbContext;
if (dbContext == null)
{
dbContext =new MyDbContext();
CallContext.SetData("DbContext",dbContext);
}
return dbContext;
为什么用EF而不用原生的Ado.Net?
1、极大的提高开发效率:EF是微软自己的产品,跟VS开发工具集成度比较好,开发中代码都是强类型的,写代码效率非常高,自动化程度非常高,命令式的编程。
2、EF提供的模型设计器非常强大,不仅仅带来了设计数据库的革命,也附带来的自动化生成模型代码的功能也极大的提高开发和架构设计的效率
3、EF跨数据支持是ORM框架主要功能点之一,带来的是可以通过仅仅改变配置就可以做到跨数据库的能力。
4、缺陷:性能差(生成sql脚本阶段),在复杂查询的时候生成的sql脚本效率不是很高。
1、不在数据端额外的消耗性能。
2、根据xml映射关系以及实体的状态生成相应的sql脚本。
做企业内部管理系统:
进销存、CRM、HR、OA、ERP、政务系统
MVC和WebFrom的区别:
控制器的作用:
1.接受用户的请求:表单中获取数据,从querystring或者Session、Cookie中处理用户的数据
2.调用业务逻辑层
3.把数据给前台aspx页面传递数据
控制器满足的约定:
1.以Controller结尾
2.必须非静态类
3.实现IController接口
Shared所有的控制器都可以去这个文件夹中查找视图
Action的作用:
1.处理用户的请求:Request、Response
2.调用业务逻辑
3.把数据传给View进行展示
伪静态的写法:
url: "{controller}/{action}.html",
配置一下属性:
简单的用户注册:
前台页面(aspx页面):
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>UserRegist</title>
</head>
<body>
<div>
<form action="/UserInfo/ProcessUserRegist" method="POST" >
<table>
<tr>
<td>用户名:</td><td><input type="text" name="txtName"/></td>
</tr>
<tr>
<td>密码:</td><td><input type="text" name="txtPwd"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
控制器的代码:
public ActionResult re(FormCollection collection)
public ActionResult ProcessUserRegist(string txtName,string txtPwd,ParaClass data)
{
//怎么拿到用户提交来的表单内容?
//string str = Request["txtName"];
//string str = collection["txtName"];
//Response.Write("ok" + str);
//Response.End();
return Content("ok" + txtName);//往前台输出一个字符串。等价于 Response.Write() + Response.End()
}
public class ParaClass
{
public string txtName { get; set; }
public string txtPwd { get; set; }
}
HTML.ActionLink方法:
<%= Html.ActionLink("超级链接的文本","About","Home",new {demo="sssss",mm="ss33"},new {style="Color:red",id=33,@class="ssssddd"}) %>
下拉列表:
<%= Html.DropDownList("CityList") %>
ViewData["CityList"] = new List<SelectListItem>()
{
new SelectListItem(){Selected = true,Text = "北京",Value ="1"},
new SelectListItem(){Selected = false,Text = "天津",Value ="2"},
new SelectListItem(){Selected = false,Text = "西红柿",Value ="3"}
};
自定义扩展方法:
namespace System.Web.Mvc//一般情况下把扩展方法所在的命名空间跟要扩展类型的命名空间搞成一致。
{
public static class MyHtmlHelper
{
public static string MyLabel(this HtmlHelper helper, string lbText)
{
return string.Format("<p>{0}</p>", lbText);
}
}
}
调用:
<%: Html.MyMvcHtmlStringLabel("sssssssskkkkkkkkkkk") %>
HTML的扩展方法:
//HtmlHelper中遇到了MvcHtmlString时候,不进行编码化处理。
public static HtmlString MyMvcHtmlStringLabel(this HtmlHelper helper, string lbText)
{
string str = string.Format("<p>{0}</p>", lbText);
return new HtmlString(str);
}
调用:
<%: Html.MyMvcHtmlStringLabel("sssssssskkkkkkkkkkk") %>
弱类型视图中传递ID的方法:
public ActionResult ShowCustomer(int id)
{
//根据id获取 当前的Customer
Customer customer = new Customer() { Id = id, Age = 18, Email = "110@itcast.cn", SName = "yang" };
ViewData["Customer"] = customer;
return View();
}
UI接受:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Import Namespace="MvcDemo2.Models" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>ShowCustomer</title>
</head>
<body>
<div>
<% var customer = ViewData["Customer"] as Customer; %>
<table>
<tr>
<td>顾客编号:</td><td><%= customer.Id %></td>
</tr>
<tr>
<td>顾客名:</td><td><%= customer.SName %></td>
</tr>
<tr>
<td>顾客Age:</td><td><%= customer.Age %></td>
</tr>
<tr>
<td>顾客邮箱:</td><td><%= customer.Email %></td>
</tr>
</table>
</div>
</body>
</html>
强类型:
#region 强类型页面的方式
public ActionResult Detail(int id)
{
//Customer customer = new Customer() { Id = id, Age = 18, Email = "110@itcast.cn", SName = "yang" };
//传一个集合的方法
List<MvcDemo2.Models.Customer> list = new List<Customer>()
{
new Customer() { Id = id, Age = 18, Email = "110@itcast.cn", SName = "yang" }
};
// ViewData["sss"] = "sssssss";
// ViewData.Model = customer;
ViewData .Model= list;
return View();
}
#endregion
页面:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.Customer>" %>
<%--<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<List<MvcDemo2.Models.Customer>>" %>--%>
<%@ Import Namespace="MvcDemo2.Models" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Detail</title>
</head>
<body>
<div>
<table>
<tr>
<td>顾客编号:</td><td><%: Model.Id %>
<%--<%: Html.TextBox("Id") %>--%>
<%-- <%: Html.TextBoxFor(c=>c.Id) %>--%>
</td>
</tr>
<tr>
<%-- <td>顾客名:</td><td><%= Model.SName %></td>--%>
<td>顾客名:</td><td><%= Model.SName %></td>
</tr>
<tr>
<%-- <td>顾客Age:</td><td><%= Model.Age %></td>--%>
<td>顾客Age:</td><td><%= Model.Age %></td>
</tr>
<tr>
<%-- <td>顾客邮箱:</td><td><%= Model.Email %></td>--%>
<td>顾客邮箱:</td><td><%= Model.Email %></td>
</tr>
</table>
</div>
</body>
</html>
MVC的增删该查:
DataModel:通过表来的
ViewModel:跟页面的表单和页面展示的内容相关
public class ClassInfoController : Controller
{
//
// GET: /ClassInfo/
CodeDbEntities dbContext = new CodeDbEntities();
public ActionResult Index(int pageIndex=1,int pageSize=2)
{
//int pageSize = int.Parse(Request["pageSize"] ?? "2");
ViewData["pageIndex"] = pageIndex;
ViewData["pageSize"] = pageSize;
ViewData["total"] = dbContext.ClassInfoes.Count();
//ViewData.Model = dbContext.ClassInfoes.AsEnumerable();
ViewData.Model = dbContext.ClassInfoes
.OrderBy(u => u.Id)
.Skip(pageSize*(pageIndex - 1))
.Take(pageSize).AsEnumerable();
return View();
}
#region Details
public ActionResult Details(int id)
{
//ViewData.Model = dbContext.ClassInfoes.Where(u => u.Id == id).FirstOrDefault();
ViewData.Model = dbContext.ClassInfoes.Find(id);
return View();
}
#endregion
#region Delete
public ActionResult Delete(int id)
{
ViewData.Model = dbContext.ClassInfoes.Find(id);
return View();
}
[HttpPost]
public ActionResult Delete(int id,FormCollection collection)
{
//把数据删除
ClassInfoes classInfoes =new ClassInfoes();
classInfoes.ClassInfoName = string.Empty;
classInfoes.Id = id;
dbContext.ClassInfoes.Attach(classInfoes);
dbContext.Entry(classInfoes).State = EntityState.Deleted;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
#region Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(ClassInfoes classInfoes)
{
dbContext.ClassInfoes.Add(classInfoes);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
#region Edit
public ActionResult Edit(int id)
{
ViewData.Model = dbContext.ClassInfoes.Find(id);
return View();
}
[HttpPost]
public ActionResult Edit(int id, ClassInfoes classInfoes)
{
dbContext.Entry(classInfoes).State = EntityState.Modified;
dbContext.SaveChanges();
return RedirectToAction("Index");
}
#endregion
}
添加:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.ClassInfoes>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
<script src="<%: Url.Content("~/Scripts/jquery-1.7.1.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"></script>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>ClassInfoes</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.ClassInfoName) %>
</div>
<div class="editor-field">
<%: Html.EditorFor(model => model.ClassInfoName) %>
<%: Html.ValidationMessageFor(model => model.ClassInfoName) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</body>
</html>
删除:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.ClassInfoes>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Delete</title>
</head>
<body>
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>ClassInfoes</legend>
<div class="display-label">
<%: Html.DisplayNameFor(model => model.ClassInfoName) %>
</div>
<div class="display-field">
<%: Html.DisplayFor(model => model.ClassInfoName) %>
</div>
</fieldset>
<% using (Html.BeginForm()) { %>
<p>
<input type="submit" value="Delete" /> |
<%: Html.ActionLink("Back to List", "Index") %>
</p>
<% } %>
</body>
</html>
详情:
<%--<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo2.Models.Customer>" %>--%>
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<List<MvcDemo2.Models.Customer>>" %>
<%@ Import Namespace="MvcDemo2.Models" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Detail</title>
</head>
<body>
<div>
<table>
<tr>
<td>顾客编号:</td><td><%: Model.Customer.ID%>
<%--<%: Html.TextBox("Id") %>--%>
<%-- <%: Html.TextBoxFor(c=>c.Id) %>--%>
</td>
</tr>
<tr>
<%-- <td>顾客名:</td><td><%= Model.SName %></td>--%>
<td>顾客名:</td><td><%= Model.Customer.Name %></td>
</tr>
<tr>
<%-- <td>顾客Age:</td><td><%= Model.Age %></td>--%>
<td>顾客Age:</td><td><%= Model.Customer.Age %></td>
</tr>
<tr>
<%-- <td>顾客邮箱:</td><td><%= Model.Email %></td>--%>
<td>顾客邮箱:</td><td><%= Model.Customer.Email %></td>
</tr>
</table>
</div>
</body>
</html>
分页:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcDemo2.Models.ClassInfoes>>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
<table>
<tr>
<th>
Id
</th>
<th>
<%: Html.DisplayNameFor(model => model.ClassInfoName) %>
</th>
<th></th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: item.Id %>
</td>
<td>
<%: Html.DisplayFor(modelItem => item.ClassInfoName) %>
</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>
<div id="pageNav">
<%: Html.ShowPageNavigate((int)ViewData["pageIndex"],(int)ViewData["pageSize"],(int)ViewData["total"]) %>
</div>
</body>
</html>
HTML分页的扩展方法:
//主要就是输出分页的超级链接的标签
//自定义分页Helper扩展
public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount)
{
var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
pageSize = pageSize == 0 ? 3 : pageSize;
var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数
var output = new StringBuilder();
if (totalPages > 1)
{
//if (currentPage != 1)
{//处理首页连接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize);
}
if (currentPage > 1)
{//处理上一页的连接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize);
}
else
{
// output.Append("<span class='pageLink'>上一页</span>");
}
output.Append(" ");
int currint = 5;
for (int i = 0; i <= 10; i++)
{//一共最多显示10个页码,前面5个,后面5个
if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
{
if (currint == i)
{//当前页处理
//output.Append(string.Format("[{0}]", currentPage));
output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
}
else
{//一般页处理
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
}
}
output.Append(" ");
}
if (currentPage < totalPages)
{//处理下一页的链接
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize);
}
else
{
//output.Append("<span class='pageLink'>下一页</span>");
}
output.Append(" ");
if (currentPage != totalPages)
{
output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize);
}
output.Append(" ");
}
output.AppendFormat("第{0}页 / 共{1}页", currentPage, totalPages);//这个统计加不加都行
return new HtmlString(output.ToString());
}
MVC异步
$(function () {
$("#loadingDiv").css("display", "none");
$("#bntJQAjax").click(function () {
$.ajax({
url: "/Ajax/Date", type: "Post",
data: {},
success: function (data) {
alert(data);
}
});
});
});
<input type="submit" value="获取日期" />
public ActionResult Date()
{
return Content(DateTime.Now.ToString());
}
MVC自带的异步:
需要引入的js
<script src="../../Scripts/jquery-1.7.1.js"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
$(function () {
$("#loadingDiv").css("display", "none");
$("#bntJQAjax").click(function () {
$.ajax({
url: "/Ajax/Date", type: "Post",
data: {},
success: function (data) {
alert(data);
}
});
});
});
$(function () {
$("#loadingDiv").css
})
function afterSuccess(data) {
//alert(data);
}
</script>
<form action="/Ajax/Date" data-ajax="true" data-ajax-confirm="您确认提交吗》?" data-ajax-loading="#loadingDiv" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="afterSuccess" data-ajax-update="#resultDiv" id="form0" method="post" enctype="multipart/form-data">
<input type="text" name="txtName" />
<br />
<input type="submit" value="获取日期" />
<input type="file" name="ss" />
</form>
隐式的按钮点击库:
$(function () {
$("btn").click(function () {
});
// 隐式的按钮点击库
$("input[btn-click]").click(function () {
var strFunc = $(this).attr("btn-click");
eval(strFunc + "()");
});
});
异步和同步上传图片:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>ImageUpload</title>
<script src="../../Scripts/jquery-1.7.1.js"></script>
<%--<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>--%>
<%--<script src="../../Scripts/MicrosoftAjax.js"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js"></script>--%>
<script src="../../Scripts/MyAjaxForm.js"></script>
<script type="text/javascript">
function afterUpload(data) {
$("#result").html("<img src='"+data+"' />");
}
$(function () {
$("#btnSub").click(function() {
$("#frm").ajaxSubmit({
url: "/Ajax/ProcessImgUpload",
type: "Post",
success: afterUpload
});
return false;
});
});
</script>
</head>
<body>
<div>
<%-- <% using (Ajax.BeginForm("ProcessImgUpload","Ajax",new AjaxOptions()
{
HttpMethod = "Post",
OnSuccess = "afterUpload"
}, new { enctype = "multipart/form-data" }))
{ %>
--%>
<form action="/Ajax/ProcessImgUpload" method="POST" enctype="multipart/form-data" id="frm">
<input type="file" id="img" name="imgFile" />
<input type="submit" id="btnSub" value="异步上传图片"/>
</form>
<%-- <% } %>--%>
<div id="result">
</div>
</div>
</body>
</html>
后台:
public ActionResult ImageUpload()
{
return View();
}
public ActionResult ProcessImgUpload()
{
var file= Request.Files["imgFile"];
string path = "/Upload/"+Guid.NewGuid().ToString()+ file.FileName;
file.SaveAs(Request.MapPath(path));
return Content(path);
}

浙公网安备 33010602011771号