using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ProductsEFDemo.Models
{
public partial class Product
{
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter a product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[Range(0.01, double.MaxValue, ErrorMessage = "Please enter a positive price")]
public decimal Price { get; set; }
[Required(ErrorMessage = "Please specify a category")]
public string Category { get; set; }
public byte[] ImageData { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
}
public class ProductContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
public class ProductsInitializer : DropCreateDatabaseIfModelChanges<ProductContext>
{
protected override void Seed(ProductContext context)
{
var products = new List<Product> {
new Product{ Name="袜子", Description="黑丝袜", Category="生活用品",Price=110m},
new Product{ Name="鞋子", Description="大头皮鞋", Category="生活用品", Price=125m},
new Product{ Name="手表", Description="瑞士金表", Category="装饰品 ", Price=135.5m}
};
products.ForEach(p => context.Products.Add(p));
context.SaveChanges();
}
}
}
由于我们此处覆盖了ProductContext默认的播种方法即数据的初始化方法,因此要重新注册这个DropCreateDatabaseIfModelChanges的子类
配置连接字符串【这里我使用VS2012自带的LocalDB数据库】
<connectionStrings>
<add name="ProductContext" connectionString="Data Source=(localdb)v11.0;Initial Catalog=ProductDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ProductDB.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
5.我仅仅为了测试定义使用现有的HomeController中的Index方法,并添加了一个Edit方法开查看System.ComponentModel.DataAnnotations在定义的类中所起的作用是否有效,为了测试没有什么DI这类的概念,代码如下:
private ProductContext context = new ProductContext();
public ViewResult Index()
{
return View(context.Products);
}
public ActionResult Edit(int productId)
{
var product = context.Products.FirstOrDefault(p => p.ProductID == productId);
return View(product);
}