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>

猜你喜欢

转载自www.cnblogs.com/ywkcode/p/10920740.html