在讲解之前,先来看看解决方案的架构:


1、在Nop.Core下的Domain里建立一个实体Category;
2、在Nop.Data下的Mapping\Catatog\下建立一个数据表映射CategoryMap:
using System.Data.Entity.ModelConfiguration;
using Nop.Core.Domain.Catalog;

namespace Nop.Data.Mapping.Catalog
{
    public partial class CategoryMap : EntityTypeConfiguration<Category>
    {
        public CategoryMap()
        {
            this.ToTable("Category");
            this.HasKey(c => c.Id);
            this.Property(c => c.Name).IsRequired().HasMaxLength(400);
            this.Property(c => c.Description).IsMaxLength();
            this.Property(c => c.MetaKeywords).HasMaxLength(400);
            this.Property(c => c.MetaDescription);
            this.Property(c => c.MetaTitle).HasMaxLength(400);
            this.Property(c => c.SeName).HasMaxLength(200);
            this.Property(c => c.PriceRanges).HasMaxLength(400);
            this.Property(c => c.PageSizeOptions).HasMaxLength(200);
        }
    }
}
3、在Nop.Data下建EF上下文接口IDbContext和对象NopObjectContext:
IDbContext:
using System.Collections.Generic;
using System.Data.Entity;
using Nop.Core;

namespace Nop.Data
{
    public interface IDbContext
    {
        IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity;

int SaveChanges();

IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters)
            where TEntity : BaseEntity, new();
    }
}

NopObjectContext:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Data.Mapping.Catalog;
//using Nop.Data.Mapping.Localization;

namespace Nop.Data
{
    /// <summary>
    /// Object context
    /// </summary>
    public class NopObjectContext : DbContext, IDbContext
    {
        public NopObjectContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
        }
        //public DbSet<Category> Category { get; set; }
        /// <summary>
        /// 自动加载所有的数据表映射类并映射到数据库表(这个函数是重点,这里就是替代DbSet<T>属性)
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //dynamically load all configuration
            System.Type configType = typeof(CategoryMap);   //any of your configuration classes here
            var typesToRegister = Assembly.GetAssembly(configType).GetTypes()
            .Where(type => !String.IsNullOrEmpty(type.Namespace))
            .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
            //...or do it manually below. For example,
            //modelBuilder.Configurations.Add(new LanguageMap());

base.OnModelCreating(modelBuilder);
        }
        /// <summary>
        /// 将一个实体附加到Context上和返回已附加这个实体(if it was already attached)
        /// </summary>
        /// <typeparam name="TEntity">TEntity</typeparam>
        /// <param name="entity">Entity</param>
        /// <returns>Attached entity</returns>
        protected virtual TEntity AttachEntityToContext<TEntity>(TEntity entity) where TEntity : BaseEntity, new()
        {
            //little hack here until Entity Framework really supports stored procedures
            //otherwise, navigation properties of loaded entities are not loaded until an entity is attached to the context
            var alreadyAttached = Set<TEntity>().Local.Where(x => x.Id == entity.Id).FirstOrDefault();
            if (alreadyAttached == null)
            {
                //attach new entity
                Set<TEntity>().Attach(entity);
                return entity;
            }
            else
            {
                //entity is already loaded.
                return alreadyAttached;
            }
        }

public string CreateDatabaseScript()
        {
            return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
        }
        /// <summary>
        /// context附加实体
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
        {
            return base.Set<TEntity>();
        }
        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="commandText"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new()
        {
            //HACK: Entity Framework Code First doesn't support doesn't support output parameters
            //That's why we have to manually create command and execute it.
            //just wait until EF Code First starts support them
            //
            //More info: http://weblogs.asp.net/dwahlin/archive/2011/09/23/using-entity-framework-code-first-with-stored-procedures-that-have-output-parameters.aspx

bool hasOutputParameters = false;
            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    var outputP = p as DbParameter;
                    if (outputP == null)
                        continue;

if (outputP.Direction == ParameterDirection.InputOutput ||
                        outputP.Direction == ParameterDirection.Output)
                        hasOutputParameters = true;
                }
            }

var context = ((IObjectContextAdapter)(this)).ObjectContext;
            if (!hasOutputParameters)
            {
                //no output parameters
                var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList();
                for (int i = 0; i < result.Count; i++)
                    result[i] = AttachEntityToContext(result[i]);

return result;

//var result = context.ExecuteStoreQuery<TEntity>(commandText, parameters).ToList();
                //foreach (var entity in result)
                //    Set<TEntity>().Attach(entity);
                //return result;
            }
            else
            {

//var connection = context.Connection;
                var connection = this.Database.Connection;
                //Don't close the connection after command execution

//open the connection for use
                if (connection.State == ConnectionState.Closed)
                    connection.Open();
                //create a command object
                using (var cmd = connection.CreateCommand())
                {
                    //command to execute
                    cmd.CommandText = commandText;
                    cmd.CommandType = CommandType.StoredProcedure;

// move parameters to command object
                    if (parameters != null)
                        foreach (var p in parameters)
                            cmd.Parameters.Add(p);

//database call
                    var reader = cmd.ExecuteReader();
                    //return reader.DataReaderToObjectList<TEntity>();
                    var result = context.Translate<TEntity>(reader).ToList();
                    for (int i = 0; i < result.Count; i++)
                        result[i] = AttachEntityToContext(result[i]);
                    //close up the reader, we're done saving results
                    reader.Close();
                    return result;
                }

}
        }
    }
}
4、在Nop.Core下的Data里建立一个接口IRepository,代码如下:
using System.Linq;

namespace Nop.Core.Data
{
    /// <summary>
    /// Repository
    /// </summary>
    public partial interface IRepository<T> where T : BaseEntity
    {
        T GetById(object id);
        void Insert(T entity);
        void Update(T entity);
        void Delete(T entity);
        IQueryable<T> Table { get; }
    }
}

5、在Nop.Core下的Data里建立一个实体EfRepository.cs,代码如下:
using System;
using System.Data.Entity;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;

namespace Nop.Data
{
    /// <summary>
    /// Entity Framework repository
    /// </summary>
    public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
    {       
        private readonly DbContext _context;
        private IDbSet<T> _entities;

/// <summary>
        /// Ctor
        /// </summary>
        /// <param name="context">Object context</param>
        public EfRepository(DbContext context)
        {
            this._context = context;
        }

public T GetById(object id)
        {
            return this.Entities.Find(id);
        }

public void Insert(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

this.Entities.Add(entity);

this._context.SaveChanges();
            }
            catch (Exception dbEx)
            {
                var msg = string.Empty;

//foreach (var validationErrors in dbEx.EntityValidationErrors)
                //    foreach (var validationError in validationErrors.ValidationErrors)
                //        msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;

var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

public void Update(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

this._context.SaveChanges();
            }
            catch (Exception dbEx)
            {
                var msg = string.Empty;

//foreach (var validationErrors in dbEx.EntityValidationErrors)
                //    foreach (var validationError in validationErrors.ValidationErrors)
                 //       msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

public void Delete(T entity)
        {
            try
            {
                if (entity == null)
                    throw new ArgumentNullException("entity");

this.Entities.Remove(entity);

this._context.SaveChanges();
            }
            catch (Exception dbEx)
            {
                var msg = string.Empty;

// foreach (var validationErrors in dbEx.EntityValidationErrors)
                //    foreach (var validationError in validationErrors.ValidationErrors)
                 //       msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

var fail = new Exception(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }

public virtual IQueryable<T> Table
        {
            get
            {
                return this.Entities;
            }
        }

private IDbSet<T> Entities
        {
            get
            {
                if (_entities == null)
                    _entities = _context.Set<T>();
                return _entities;
            }
        }
        //TODO implement IDisposable interface
    }
}

 6、在Nop.Services中建立ICategoryService和CategoryService:
ICategoryService:

using System.Collections.Generic;
using Nop.Core;
using Nop.Core.Domain.Catalog;

namespace Nop.Services.Catalog
{
    /// <summary>
    /// Category service interface
    /// </summary>
    public partial interface ICategoryService
    {

/// <summary>
        /// Gets all categories
        /// </summary>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Categories</returns>
        IList<Category> GetAllCategories(bool showHidden = false);

}
}

CategoryService:
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Data;

namespace Nop.Services.Catalog
{
    /// <summary>
    /// Category service
    /// </summary>
    public partial class CategoryService : DbModelBuilder,ICategoryService
    {
        #region Constants
        //private const string CATEGORIES_BY_ID_KEY = "Nop.category.id-{0}";

#endregion

#region Fields

private readonly IRepository<Category> _categoryRepository;
        //private readonly DbProviderFactory _dbProviderFactory;
        #endregion

#region Ctor

public CategoryService()
        {
            var ConnectionString = "Data Source=192.168.16.2;Initial Catalog=nopCommerce;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=123456;MultipleActiveResultSets=True";
            DbContext dbContext = new NopObjectContext(ConnectionString);
          
            this._categoryRepository = new EfRepository<Category>(dbContext);
           
        }

#endregion

#region Methods

/// <summary>
        /// Gets all categories
        /// </summary>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Categories</returns>
        public virtual IList<Category> GetAllCategories(bool showHidden = false)
        {
            var query = from c in _categoryRepository.Table
                        orderby c.ParentCategoryId, c.DisplayOrder
                        where (showHidden || c.Published) &&
                        !c.Deleted
                        select c;

var unsortedCategories = query.ToList();

return unsortedCategories;
        }

#endregion
    }
}

EF4.1 企业架构模式 自动映射数据表(转载)的更多相关文章

  1. SpringBoot+Mybatis 自动创建数据表(适用mysql)

    Mybatis用了快两年了,在我手上的发展史大概是这样的 第一个阶段 利用Mybatis-Generator自动生成实体类.DAO接口和Mapping映射文件.那时候觉得这个特别好用,大概的过程是这样 ...

  2. hibernate中.hbm.xml和注解方式自动生成数据表的简单实例(由新手小白编写,仅适用新手小白)

    绝逼新手小白,so 请大神指点! 如果真的错的太多,错的太离谱,错的误导了其他小伙伴,还望大神请勿喷,大神请担待,大神请高抬贵嘴......谢谢. 好了,正题 刚接触ssh,今天在搞使用.hbm.xm ...

  3. A.CTable 自动创建数据表

    1.添加依赖 <!-- A.CTable 自动创建数据表 --> <dependency> <groupId>com.gitee.sunchenbin.mybati ...

  4. springboot项目启动-自动创建数据表

    很多时候,我们部署一个项目的时候,需要创建大量的数据表.例如mysql,一般的方法就是通过source命令完成数据表的移植,如:source /root/test.sql.如果我们需要一个项目启动后, ...

  5. generator自动生成数据表

    1.先写好自己要创建的字段等: 然后将将上面的在plsql中运行,创建数据表.

  6. Hibernate不能自动建数据表解决办法

    首先自己要注意自己的MYSQL版本,然后设置对应的方言 兼容性模式 <property name="hibernate.dialect">org.hibernate.d ...

  7. Automap sqlalchemy.ext.automap 自动映射数据库表结构

    from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy i ...

  8. Microservice架构模式简介

    在2014年,Sam Newman,Martin Fowler在ThoughtWorks的一位同事,出版了一本新书<Building Microservices>.该书描述了如何按照Mic ...

  9. IT忍者神龟之Hibernat持久化对象-数据表映射配置回想

    1.持久化对象POJO编写规则: 1) 有空參public构造器: 2) 提供标识属性.映射数据表主键: 3) 属性提供setter和getter方法. 4) 属性使用基本数据类型的包装类型.基本类型 ...

随机推荐

  1. Linux下OOM Killer机制详解

    http://www.cnblogs.com/ylqmf/archive/2012/11/05/2754795.html http://wuquan-1230.blog.163.com/blog/st ...

  2. DotNet.Utilities工具类

    来源:http://git.oschina.net/kuiyu/dotnetcodes/tree/master/DotNet.Utilities

  3. redis+spring配置

    pom引入jedis的jar包 <dependency> <groupId>redis.clients</groupId> <artifactId>je ...

  4. shiro+redis实现session共享

    shiro配置内容

  5. .NET:负载平衡的主意事项

    允许局域网发现和共享. 设置固定IP. 网站的IP设置为“全部未分配”. 注意:如果停止IIS的话,不会对负载平衡有影响,负载还是会分配停止了的IIS所在在的电脑,只有停止服务器了,负载不会再分配给停 ...

  6. java.lang.Integer can not be cast to java.lang.Long

    hibernate 查询出来的结果 id 是int类型,xml文件配置的是int, 在jython 中调用hibernate 进行查询.字段的类型是java.lang.Long, 直接将id 传进去, ...

  7. iOS:上线的基本流程

    1.创建唯一标书符App ID 首先打开开发者网站,进入证书页面,我们点击Identifiers下边App IDs选项,然后点击右上角加号,如图: 2.申请发布证书 我们点击Certificates下 ...

  8. iOS:分组的表格视图UITableView,可以折叠和展开

    虽然表格视图可以分组,但是如果分组后,每一行的内容太多,往后翻看起来比较的麻烦.为了解决这个麻烦,可以将分组的行折叠和展开.折叠时,行内容就会隐藏起来:展开时,行内容就会显示出来. 折叠时: 展开后: ...

  9. SPSS Clementine 数据挖掘入门1

    SPSS Clementine是Spss公司收购ISL获得的数据挖掘工具.在Gartner的客户数据挖掘工具评估中,仅有两家厂商被列为领导者:SAS和SPSS.SAS获得了最高ability to e ...

  10. OpenMP 线程互斥锁

    OpenMP是跨平台的多核多线程编程的一套指导性的编译处理方案(Compiler Directive),指导编译器将代码编译为多线程程序. 多线程编程中肯定会涉及到线程之间的资源共享问题,就可以使用互 ...