MVC5与EF6 Code First 第一个入门完整实例教程

来源:互联网 发布:域名注册空间商网站 编辑:程序博客网 时间:2024/05/29 07:02

经过实例测试,在创建上下文时,就是创建数据库的时候,不过在新的EF框架中,貌似默认的时先链接数据库,若发现不存在,则创建。因此,若更新数据库,需要进行迁移更改,不然链接数据库会出错。



1、创建一个mvc的项目

打开VS2013新建项目一个Web项目,框架选.NET Framewok4.5,项目名字为MiniProfilerDemo。如下图:


接下来在弹出的窗口中选择项目的模板为mvc,如下图:

2、添加安装EF框架依赖包到项目

选中刚才建的项目,右键弹出以下菜单:

点击“管理nuget程序包”在下面的界面点击“安装”EntityFramework 6.1

安装成功之后,会自动添加相关的dll引用到项目中。


3、添加一个Model

选中项目中的Models文件夹,添加一个Product类:


  1. namespace MiniProfilerDemo.Models
  2. {
  3. public class Product
  4. {
  5. public int ID { get; set; }
  6. public string Name { get; set; }
  7. public decimal Price { get; set; }
  8. public int Quantity { get; set; }
  9. }
  10. }


4、添加一个EF的上下文类

为项目添加一个EF的上下文类,用来做为访问数据库的公共类:

  1. using MiniProfilerDemo.Models;
  2. using System.Data.Entity;
  3. namespace MiniProfilerDemo.DAL
  4. {
  5. public class EFDbContext:DbContext
  6. {
  7. public DbSet<Product> Products { get; set; }
  8. }
  9. }


在Web.config中加入一个数据库链接:
  1. <connectionStrings>
  2. <add name="EFDbContext" connectionString="Server=.;Database=MiniProfilerDemo;uid=sa;pwd=sa;" providerName="System.Data.SqlClient" />
  3. </connectionStrings>
注意:上面的数据库链接字符串你要根据的自己的数据库来做相应的调整,这个数据库链接的结点名字为“EFDbContext”和上面建的EF的上下文类名字一样。在EF上下文类中没有指定结点名称、默认就是类名称与数据库链接配置结点名同名,当然你在实践中也可以不一样,但是这样你的EF的上下文类就要多加一个构造函数:
  1. public EFDbContext(): base("数据库链接的结点名字")
  2. {
  3. }


5、创建一个展示Model类的Controller和视图


1、选中项目的Controller文件夹,添加一个名字为Product的Controller
  1. using MiniProfilerDemo.DAL;
  2. using System.linq;
  3. using System.Web.Mvc;
  4. namespace MiniProfilerDemo.Controllers
  5. {
  6. public class ProductController : Controller
  7. {
  8. public ActionResult Index()
  9. {
  10. using (EFDbContext db=new EFDbContext())
  11. {
  12. var m = db.Products.ToList();
  13. return View(m);
  14. }
  15. }
  16. }
  17. }
2、把光标移动到上面的Action为Index方法的内,右键弹出菜单点击“添加视图”,在里面输入下面的内容:
  1. @model List<MiniProfilerDemo.Models.Product>
  2. @{
  3. ViewBag.Title = "ProductList";
  4. }
  5. <h2>ProductList</h2>
  6. <table class="table">
  7. <thead>
  8. <tr>
  9. <th>ID</th>
  10. <th>Name</th>
  11. <th>Price</th>
  12. <th>Quantity</th>
  13. </tr>
  14. </thead>
  15. <tbody>
  16. @foreach (var item in Model)
  17. {
  18. <tr>
  19. <td>@item.ID</td>
  20. <td>@item.Name</td>
  21. <td>@item.Price</td>
  22. <td>@item.Quantity</td>
  23. </tr>
  24. }
  25. </tbody>
  26. </table>

这个视图的绑定的model类型为强类型List<MiniProfilerDemo.Models.Product>,数据记录用了一个表格展示。

6、查看页面,运行结果


第一次运行页面,是没有数据,这是正常的,因为刚开始连数据库都还没有,运行的时候EF会根据之前配置的数据库链接和EF上下文,自动创建一个数据库和Model对应的表,如下图:


下面我们手动打开表Product,添加一些记录进去

再次刷新页面就有刚才添加的数据了,如下图:

阅读全文
原创粉丝点击