您的位置:首页 > 其它

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

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

1、创建一个mvc的项目

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



接下来在弹出的窗口中选择项目的模板为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; }
}
}



在Web.config中加入一个数据库链接:
<connectionStrings>
<add name="EFDbContext" connectionString="Server=.;Database=MiniProfilerDemo;uid=sa;pwd=sa;" providerName="System.Data.SqlClient" />
</connectionStrings>


注意:上面的数据库链接字符串你要根据的自己的数据库来做相应的调整,这个数据库链接的结点名字为“EFDbContext”和上面建的EF的上下文类名字一样。在EF上下文类中没有指定结点名称、默认就是类名称与数据库链接配置结点名同名,当然你在实践中也可以不一样,但是这样你的EF的上下文类就要多加一个构造函数:
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);
}
}
}
}


2、把光标移动到上面的Action为Index方法的内,右键弹出菜单点击“添加视图”,在里面输入下面的内容:
@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对应的表,如下图:



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



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



阅读全文
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: