-
EntityFrame技术
EntityFrame是微软公司提供的一种动态数据技术,能够很好地与数据库建立起关系,免去了繁琐的手写SQL语句的操作。EntityFrame也是使用ADO.NET组件去实现数据库连接等操作的,但是开发人员不用关心如何去连接数据库了,只需可视化操作就能实现数据库数据模型的建立,实质上使用的就是对象关系映射:
表→实体类
字段→属性
实体→对象
建立步骤:鼠标右击Model文件夹>>新建项>>数据>>ADO.NET实体模型,选择相应的数据库和数据表建立模型即可。
注意:使用EntityFramework之前,请为数据表设置主键、主外键关系!
-
ASP.NET MVC数据传递
ViewBag数据传递、Model数据绑定、form提交数据。
-
ASP.NET MVC小练习
案例:使用ASP.NET MVC+EntityFramework实现商品管理系统
数据库设计及其表结构:
create database GoodsSystem
go
use GoodsSystem
go
--商品类别表
create table Category
(
Category_Id int not null primary key identity(1,1),--主键、标识
Category_Name varchar(50) not null
)
go
insert into Category(Category_Name) values('零食')
insert into Category(Category_Name) values('水果')
insert into Category(Category_Name) values('蔬菜')
insert into Category(Category_Name) values('日用')
go
--商品信息表
create table Goods
(
Goods_Id int not null primary key identity(1,1),--主键、标识
Goods_Name varchar(50) not null,
Goods_Img varchar(50) not null,--商品实图[一般还是保存磁盘上图片的文件名]
Goods_Price money not null,
Category_Id int not null references Category(Category_Id)--外键[商品类别]
)
go
insert into Goods(Goods_Name,Goods_Img,Goods_Price,Category_Id)
values('三只松鼠大礼包','三只松鼠.jpg','455.8',1)
insert into Goods(Goods_Name,Goods_Img,Goods_Price,Category_Id)
values('哈密瓜','哈密瓜.jpg','33.4',2)
insert into Goods(Goods_Name,Goods_Img,Goods_Price,Category_Id)
values('脆皮黄瓜','黄瓜.jpg','9.9',3)
insert into Goods(Goods_Name,Goods_Img,Goods_Price,Category_Id)
values('避孕套','避孕套.jpg','233.4',4)
go
select * from Goods,Category where Goods.Category_Id=Category.Category_Id
go
搭建ASP.NET Web MVC框架,新建Main控制器,源代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
//导入实体模型命名空间
using GoodsSystem.Models;
namespace GoodsSystem.Controllers
{
public class MainController : Controller
{
//建立视图模型对象
GoodsSystemEntities db = new GoodsSystemEntities();
// 商品信息主页视图
public ActionResult Index()
{
//将所有的商品信息以模型传递到视图
return View(db.Goods.ToList());
}
//表单提交数据:查询商品
[HttpGet]
public ActionResult Index(string searchKeys, int ? Category_Id)
{
var list = db.Goods.ToList();
if(!string.IsNullOrEmpty(searchKeys))
{
list = list.Where(a => a.Goods_Name.Contains(searchKeys)).ToList();
}
if(Category_Id>0)
{
list = list.Where(a => a.Category_Id==Category_Id).ToList();
}
return View(list);
}
//添加商品信息视图
public ActionResult AddGoods()
{
return View(new Good());
}
//表单提交数据:请求添加商品信息
[HttpPost]
public ActionResult AddGoods(Good m,HttpPostedFileBase goodsImgFile)
{
/*求得上传的商品图片物理路径*/
var fileName = Request.MapPath("/img/") + goodsImgFile.FileName;
/*保存上传的商品图片*/
goodsImgFile.SaveAs(fileName);
/*给模型商品图片属性赋值:图片属性与其他属性稍有不同*/
m.Goods_Img = goodsImgFile.FileName;
/*添加模型*/
db.Goods.Add(m);
/*保存更改*/
db.SaveChanges();
/*重定向到主页*/
return RedirectToAction("Index","Main");
}
//编辑商品信息视图
public ActionResult EditGoods(int goods_id)
{
//传递模型:依据商品编号查找模型
return V