ASP.NET MVC 4 Model – Code First Sample ( Generate Table Structure )

ASP.NET MVC 4 Model – Code First Sample ( Generate Table Structure )

   \Models\Product.cs
 
   using System;
 
   namespace CRMPortal.Models
   {
      public class Product
      {
         public int ID { get; set; }
         public int Category { get; set; }
         public int SubCategory { get; set; }
         public String Model { get; set; }
         public float Price { get; set; }
      }
   }
 
   \Models\ProductContext.cs
 
   using System;
   using System.Data.Entity;
 
   namespace CRMPortal.Models
   {
      public class ProductContext : DbContext
      {
         public DbSet<Product> Product { get; set; }
         public ProductContext() : base("DefaultConnection")
         {
         }
      }
   }
 
   \Controllers\HomeController.cs
 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Web;
   using System.Web.Mvc;
   using CRMPortal.Models;
 
   namespace CRMPortal.Controllers
   {
      public class HomeController : Controller
      {
 
         public ActionResult Index()
         {
            using (var db = new ProductContext())
            {
               Product p = new Product();
               p.ID = 1;
               p.Category = 1;
               p.SubCategory = 1;
               p.Model = "Model 1";
               p.Price = 100;
 
               db.Product.Add(p);
               db.SaveChanges();
 
               return View();
            }
         }
 
         … …
 
      }
   }
 
   更改 web.conf 下列部分
 
   <connectionStrings>
      <add name="DefaultConnection"
            connectionString="Data Source=(LocalDb)\v110;… …;Initial Catalog=aspnet-DbMigrationExample;Integrated Security=True"
            providerName="System.Data.SqlClient" />
   </connectionStrings>
 
 
   <connectionStrings>
      <add name="DefaultConnection"
               connectionString="Data Source=VMSER001;Initial Catalog=MVCIdentity;Persist Security Info=True;User ID=sa;Password=P@ssw0rd"
               providerName="System.Data.SqlClient" />
   </connectionStrings>