码迷,mamicode.com
首页 > Web开发 > 详细

3.MVC基础-Code First 入门完整实例

时间:2019-05-24 23:46:35      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:test   base   控制器   list()   head   一个数据库   数据库连接   ant   meta   

1.添加一个EF的上下文类  EFDbContext
1 public class EFDbContext:DbContext
2 {
3         public EFDbContext() : base("EFDbContext")
4         {
5         }
6         public DbSet<Product> Product { get; set; }
7 }

 

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

 

3.在EFDbContext中 增加构造函数
public EFDbContext() : base("EFDbContext")
 
4.添加Model
public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
    }

 

 
5.新建控制器 
1  public ActionResult Index()
2  {
3       using (EFDbContext db = new EFDbContext())
4     {
5          var productlist = db.Product.ToList();
6          return View(productlist);
7      }
8  }

 

6.创建视图
@model List<MVCEF.Models.Product>
@{
    ViewBag.Title = "ProductList";
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <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>
</body>
</html>

 

3.MVC基础-Code First 入门完整实例

标签:test   base   控制器   list()   head   一个数据库   数据库连接   ant   meta   

原文地址:https://www.cnblogs.com/ywkcode/p/10920740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!