zoukankan      html  css  js  c++  java
  • 3.MVC基础-Code First 入门完整实例

    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>
    
  • 相关阅读:
    乘法逆元
    17-11-01模拟赛
    17/10-17/11做题记录
    17-10-18模拟赛
    17-10-15模拟赛
    13-2.模板复习priority_queue
    bzoj1042[HAOI2008]硬币购物
    bzoj1057[ZJOI2007]棋盘制作
    bzoj1029[JSOI2007]建筑抢修
    bzoj1068[SCOI2007]压缩
  • 原文地址:https://www.cnblogs.com/ywkcode/p/10920740.html
Copyright © 2011-2022 走看看