Loading

NopCommerce 3.80框架研究(一) 数据访问与持久化

NopCommerce 是一个国外的开源电商系统。3.80版本使用EF6.0 和.Net Framework 4.5.1

并引入了AutofacAutofac是一款IOC框架,比较于其他的IOC框架,如Spring.NETUnityCastle等等所包含的,它很轻量级 性能上非常高。

关于 Autofac 可以参考 原油 的文章 http://www.cnblogs.com/jys509/p/4649798.html

本系列文章要用于记录研究笔记,废话不多可以当参考文档看看。

下面将会以 项目名称\主要文件夹名称的格式介绍二次开发主要涉及的内容、而非插件开发

插件开发可参考官方文档,也有类似的内容 :Plugin with data access

   

解决方案结构:

  1. Nop.Core\Domain\

    此文件夹主要存放Code First的数据库实体对象

    字段对应数据库,Id 属性继承自BaseEntity 无需再写

    如下代码:

    using System;

    using Nop.Core.Domain.Customers;

    namespace Nop.Core.Domain.Blogs

    {

    ///

    /// Represents a blog comment

    ///

    public partial class BlogComment : BaseEntity

    {

    public int CustomerId { get; set; }

    public string CommentText { get; set; }

  2. Nop.Data\ Mapping

    文件夹中的类型主要描述 Nop.Core\Domain\ 文件夹中的对象对于数据库表的映射关系与约束

    public partial class CountryMap : NopEntityTypeConfiguration<Country>

    {

    public CountryMap()

    {

    this.ToTable("Country"); //数据库表名称

    this.HasKey(c =>c.Id);//主键 如果自己新增的数据表则必须设置为自增长

         //经测试如下代码对于后期建立的表无效

    //this.Property(o => o.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);

    this.Property(c => c.Name).IsRequired().HasMaxLength(100);

    this.Property(c =>c.TwoLetterIsoCode).HasMaxLength(2);

    this.Property(c =>c.ThreeLetterIsoCode).HasMaxLength(3);

    }

    }

    框架不会使ID自动增长然后插入,必须手动设置数据库表字段属性为自动增长,在执行Insert语句之后框架会自动查询已插入的ID 值

    如在SQL Server 中这个SQL语句可以在执行完插入动作后自动返回已增长的ID值:

    Insert into Table xxx;Select @@Identity

   

  1. Nop.Services\

    主要定义数据操作和业务逻辑

    基本上每个操作类都有一个对应的接口,如果需要新增自己的业务对象则应该参照如下步骤:

  • 定义你的操作类
  • 从操作类中提取接口
  • 指定注入类型

如:下图中 IRepository<Customer> _customerRepository 表示数据仓库的操作对象,

IGenericAttributeService _genericAttributeService; 这个类型类似于CustomerService的定义,也是有一个接口和一个实现类

它们都将在Nop.Web.Framework.DependencyRegistrar.Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) 方法中定义如何自动注入

   

   

  

posted @ 2016-09-14 11:03  韩严重  阅读(4804)  评论(0编辑  收藏  举报