mvc如今火的不行,我今天就来介绍一个MVC5与EF6开发的实际的入门实例,因为EF6默认是Code First的,所以我今天也就用EF6 的Code First来做一个简单的实例,为了让实例显得简单,这里面就用一个表,用来展示一个表的记录,model和dal也都在一个项目中。下面是详细步骤:
1、创建一个mvc的项目
打开VS2013新建项目一个Web项目,框架选.NET Framewok4.5,项目名字为MiniProfilerDemo。如下图:
![](http://www.lanhusoft.com/attached/image/20150207/20150207205824_3092.gif)
接下来在弹出的窗口中选择项目的模板为mvc,如下图:
2、添加安装EF框架依赖包到项目
选中刚才建的项目,右键弹出以下菜单:
点击“管理nuget程序包”在下面的界面点击“安装”EntityFramework 6.1
安装成功之后,会自动添加相关的dll引用到项目中。
3、添加一个Model
选中项目中的Models文件夹,添加一个Product类:
- namespace MiniProfilerDemo.Models
- {
- public class Product
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public decimal Price { get; set; }
- public int Quantity { get; set; }
- }
- }
4、添加一个EF的上下文类
为项目添加一个EF的上下文类,用来做为访问数据库的公共类:
- using MiniProfilerDemo.Models;
- using System.Data.Entity;
- namespace MiniProfilerDemo.DAL
- {
- public class EFDbContext:DbContext
- {
- public DbSet<Product> Products { get; set; }
- }
- }
- <connectionStrings>
- <add name="EFDbContext" connectionString="Server=.;Database=MiniProfilerDemo;uid=sa;pwd=sa;" providerName="System.Data.SqlClient" />
- </connectionStrings>
- public EFDbContext(): base("数据库链接的结点名字")
- {
- }
5、创建一个展示Model类的Controller和视图
1、选中项目的Controller文件夹,添加一个名字为Product的Controller
- using MiniProfilerDemo.DAL;
- using System.linq;
- using System.Web.Mvc;
- namespace MiniProfilerDemo.Controllers
- {
- public class ProductController : Controller
- {
- public ActionResult Index()
- {
- using (EFDbContext db=new EFDbContext())
- {
- var m = db.Products.ToList();
- return View(m);
- }
- }
- }
- }
- @model List<MiniProfilerDemo.Models.Product>
- @{
- ViewBag.Title = "ProductList";
- }
- <h2>ProductList</h2>
- <table class="table">
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Price</th>
- <th>Quantity</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model)
- {
- <tr>
- <td>@item.ID</td>
- <td>@item.Name</td>
- <td>@item.Price</td>
- <td>@item.Quantity</td>
- </tr>
- }
- </tbody>
- </table>
这个视图的绑定的model类型为强类型List<MiniProfilerDemo.Models.Product>,数据记录用了一个表格展示。
6、查看页面,运行结果
第一次运行页面,是没有数据,这是正常的,因为刚开始连数据库都还没有,运行的时候EF会根据之前配置的数据库链接和EF上下文,自动创建一个数据库和Model对应的表,如下图:
![](http://www.lanhusoft.com/attached/image/20150207/20150207210157_8561.gif)
下面我们手动打开表Product,添加一些记录进去
再次刷新页面就有刚才添加的数据了,如下图: