MVC(MyStoreEntities)

Entity Framework(EF框架)

  • Entity Framework负责将模型与数据库关联起来
  • Entity Framework需要两件事以实现它的上述目的
  1. 创建一个上下文类(MyStoreEntities)==>连接到数据库后Entity Framework会自动生成它
  2. 在连接到数据库后,在web.config文件中增添连接串,这个连接串的名字与上下文类的名字相同==>需要开发者手动添加

    
  

MyStoreEntities

public partial class MyStoreEntities : DbContext
    {
        public MyStoreEntities()
            : base("name=MyStoreEntities")
        {
        }
        ......
        public virtual DbSet Category { get; set; }
        public virtual DbSet Product { get; set; }
        ......
    }
  • MyStoreEntities继承于上下文类DbContext
  • MyStoreEntities具有DbSet(模型)类型的属性,其值对应数据库的每张表
  • 我们通常通过MyStoreEntities的实例来对数据库进行读写,具体有如下应用

实现存储库类

public class EFProductRepository:IProductsRepository
    {
        private MyStoreEntities db = new MyStoreEntities();
        public IQueryable Products
        {
            get { return db.Product; }
        }
        public IQueryable Categories
        {
            get { return db.Category; }
        }
        public IQueryable Customers
        {
            get { return db.Customer; }
        }
    }

实现业务处理类

  public class DatabaseOrderProcessor : IOrderProcessor
    {
        public void ProcessOrder(Cart cart, ShippingAddress shippingInfo, Customer customer)
        {         
                       var db = new MyStoreEntities()
                        Order order = new Order();
                        order.CustomerId = customer.Id;
                        order.OrderDate = DateTime.Now;
                        .......
                        db.Order.Add(order);//修改db属性
                        db.SaveChanges();//db向数据库提交改变
            }
        }
    }

你可能感兴趣的:(MVC(MyStoreEntities))