个人项目框架搭建 -- 仓储模式使用

---恢复内容开始---

1、创建仓储模式的相关接口

2、三个文件的代码(命名空间)

IRepository.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace EnterpriseFrame.Core.Data
{
    /// <summary>
    /// 这里T是泛型,(T:class  T是泛型参数。where T : class  是对T的限制,这里的意思是T必须是引用类型,包括任何类、接口、委托或数组类型)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IRepository<T> where T : class
    {

        /// <summary>
        /// Gets a table
        /// </summary>
        IQueryable<T> Table { get; }
        /// <summary>
        /// IRespository插入接口
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        bool InsertEntity(T entity);

        /// <summary>
        /// IRespository修改接口
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        bool UpdateEntity(T entity);

        /// <summary>
        /// IRespository删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        bool DeleteEntity(T entity);

        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        T GetEntityById(object Id);

        /// <summary>
        /// 带条件查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        T Get(Expression<Func<T, bool>> where);

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        IEnumerable<T> GetALLEntity();

        /// <summary>
        /// 这里也可以用IEnumerable类型,带条件查询所有
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        IQueryable<T> GetAllEntityWhere(Expression<Func<T, bool>> where);

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        IList<T> GetPageEntities(int pageIndex, int PageSize);

        /// <summary>
        /// 分页带查询条件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        IList<T> GetPageEntities(int pageIndex, int PageSize, Expression<Func<T, bool>> where);

    }
}

IRepository

EfRepository.cs代码:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EnterpriseFrame.Core.Data
{
    public class EfRepository<T> : IRepository<T> where T : class
    {

        private readonly IDbContext _context;
        private IDbSet<T> _entities;

        public EfRepository(IDbContext context)
        {
            this._context = context;
        }

        protected virtual IDbSet<T> Entities
        {
            get
            {
                if (_entities == null)
                    _entities = _context.Set<T>();
                return _entities;
            }
        }
        /// <summary>
        /// Gets a table
        /// </summary>
        public virtual IQueryable<T> Table
        {
            get
            {
                return this.Entities;
            }
        }

        /// <summary>
        /// 插入实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool InsertEntity(T entity)
        {
            bool RetStatus = false;
            this.Entities.Add(entity);
            if (Save() > 0)
            {
                RetStatus = true;
            }
            return RetStatus;

        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateEntity(T entity)
        {
            // throw new NotImplementedException();
            bool RetStatus = false;
            if (entity != null && Save() > 0)
            {
                RetStatus = true;
            }
            return RetStatus;

        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            //throw new NotImplementedException();
            bool RetStatus = false;
            if (entity != null)
            {
                this.Entities.Remove(entity);
                if (Save() > 0)
                {
                    RetStatus = true;
                }
            }
            return RetStatus;

        }

        /// <summary>
        /// 对Set<T>根据id 的查询的操作
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public T GetEntityById(object Id)
        {
            return this.Entities.Find(Id);
        }

        /// <summary>
        /// 这里对Set<T>是带条件的操作
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public T Get(Expression<Func<T, bool>> where)
        {
            return this.Entities.Where(where).FirstOrDefault<T>();
        }

        /// <summary>
        /// 查询所有的
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> GetALLEntity()
        {
            //  throw new NotImplementedException();

            IEnumerable<T> query = this.Entities;

            return query;
        }

        /// <summary>
        /// 查询所有带条件
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public IQueryable<T> GetAllEntityWhere(Expression<Func<T, bool>> where)
        {
            IQueryable<T> query = this.Entities.Where(where);
            return query;

        }

        /// <summary>
        /// 分页方法
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="PageSize"></param>
        /// <returns></returns>
        public IList<T> GetPageEntities(int pageIndex, int PageSize)
        {
            IList<T> List = this.Entities.Skip(pageIndex * PageSize).Take(PageSize).ToList();
            return List;

        }

        /// <summary>
        /// 分页带查询条件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="where"></param>
        /// <returns></returns>
        public IList<T> GetPageEntities(int pageIndex, int PageSize, Expression<Func<T, bool>> where)
        {
            // throw new NotImplementedException();
            IList<T> List = this.Entities.Where(where).Skip(pageIndex * PageSize).Take(PageSize).ToList();
            return List;

        }

        /// <summary>
        /// Save 保存确认方法
        /// </summary>
        public int Save()
        {
            return this._context.SaveChanges();

        }
    }
}

EfRepository

IDbContext.cs:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EnterpriseFrame.Core.Data
{
    public interface IDbContext
    {
        /// <summary>
        /// Get DbSet
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <returns>DbSet</returns>
        IDbSet<TEntity> Set<TEntity>() where TEntity : class;

        /// <summary>
        /// Save changes
        /// </summary>
        /// <returns></returns>
        int SaveChanges();

        /// <summary>
        /// Execute stores procedure and load a list of entities at the end
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <param name="commandText">Command text</param>
        /// <param name="parameters">Parameters</param>
        /// <returns>Entities</returns>
        IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters)
            where TEntity : class, new();

        /// <summary>
        /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
        /// </summary>
        /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
        /// <param name="sql">The SQL query string.</param>
        /// <param name="parameters">The parameters to apply to the SQL query string.</param>
        /// <returns>Result</returns>
        IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters);

        /// <summary>
        /// Executes the given DDL/DML command against the database.
        /// </summary>
        /// <param name="sql">The command string</param>
        /// <param name="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</param>
        /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
        /// <param name="parameters">The parameters to apply to the command string.</param>
        /// <returns>The result returned by the database after executing the command.</returns>
        int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters);
    }
}

IDbContext

3、在EF CodeFirst中使用

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 System.Text;
using System.Threading.Tasks;

namespace EnterpriseFrame.Entity
{
    using EnterpriseFrame.Core.Data;

    public partial class EnterpriseContext : DbContext, IDbContext
    {
        public EnterpriseContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }
        #region Entity
        public virtual DbSet<Admin> Admins { get; set; }
        public virtual DbSet<ArticleInfo> ArticleInfoes { get; set; }
        public virtual DbSet<ArticleRelation> ArticleRelations { get; set; }
        public virtual DbSet<ArticleType> ArticleTypes { get; set; }
        public virtual DbSet<FriendsLink> FriendsLinks { get; set; }
        public virtual DbSet<Permission> Permissions { get; set; }
        public virtual DbSet<Role_Permission> Role_Permission { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<SiteALlConfig> SiteALlConfigs { get; set; }
        public virtual DbSet<SiteMessage> SiteMessages { get; set; }
        #endregion

        #region Utilities

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //dynamically load all configuration
            //System.Type configType = typeof(LanguageMap);   //any of your configuration classes here
            //var typesToRegister = Assembly.GetAssembly(configType).GetTypes()

            var typesToRegister = Assembly.GetExecutingAssembly().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());

            modelBuilder.Entity<ArticleInfo>()
                .Property(e => e.ArtContent)
                .IsUnicode(false);

            modelBuilder.Entity<SiteMessage>()
                .Property(e => e.MsgContent)
                .IsUnicode(false);

            modelBuilder.Entity<SiteMessage>()
                .Property(e => e.MsgReply)
                .IsUnicode(false);

            base.OnModelCreating(modelBuilder);
        }
        #endregion

        #region Methods

        /// <summary>
        /// Create database script
        /// </summary>
        /// <returns>SQL to generate database</returns>
        public string CreateDatabaseScript()
        {
            return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
        }

        /// <summary>
        /// Get DbSet
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <returns>DbSet</returns>
        public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }

        /// <summary>
        /// Execute stores procedure and load a list of entities at the end
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <param name="commandText">Command text</param>
        /// <param name="parameters">Parameters</param>
        /// <returns>Entities</returns>
        public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : class, new()
        {
            //add parameters to command
            if (parameters != null && parameters.Length > 0)
            {
                for (int i = 0; i <= parameters.Length - 1; i++)
                {
                    var p = parameters[i] as DbParameter;
                    if (p == null)
                        throw new Exception("Not support parameter type");

                    commandText += i == 0 ? " " : ", ";

                    commandText += "@" + p.ParameterName;
                    if (p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Output)
                    {
                        //output parameter
                        commandText += " output";
                    }
                }
            }

            var result = this.Database.SqlQuery<TEntity>(commandText, parameters).ToList();

            //performance hack applied as described here - http://www.nopcommerce.com/boards/t/25483/fix-very-important-speed-improvement.aspx
            bool acd = this.Configuration.AutoDetectChangesEnabled;
            try
            {
                this.Configuration.AutoDetectChangesEnabled = false;

                throw new System.NotImplementedException();//未实现
                //for (int i = 0; i < result.Count; i++)
                //    result[i] = AttachEntityToContext(result[i]);
            }
            finally
            {
                this.Configuration.AutoDetectChangesEnabled = acd;
            }

            return result;
        }

        /// <summary>
        /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
        /// </summary>
        /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
        /// <param name="sql">The SQL query string.</param>
        /// <param name="parameters">The parameters to apply to the SQL query string.</param>
        /// <returns>Result</returns>
        public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
        {
            return this.Database.SqlQuery<TElement>(sql, parameters);
        }

        /// <summary>
        /// Executes the given DDL/DML command against the database.
        /// </summary>
        /// <param name="sql">The command string</param>
        /// <param name="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</param>
        /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
        /// <param name="parameters">The parameters to apply to the command string.</param>
        /// <returns>The result returned by the database after executing the command.</returns>
        public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
        {
            int? previousTimeout = null;
            if (timeout.HasValue)
            {
                //store previous timeout
                previousTimeout = ((IObjectContextAdapter)this).ObjectContext.CommandTimeout;
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = timeout;
            }

            var transactionalBehavior = doNotEnsureTransaction
                ? TransactionalBehavior.DoNotEnsureTransaction
                : TransactionalBehavior.EnsureTransaction;
            var result = this.Database.ExecuteSqlCommand(transactionalBehavior, sql, parameters);

            if (timeout.HasValue)
            {
                //Set previous timeout back
                ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = previousTimeout;
            }

            //return result
            return result;
        }

        #endregion
    }
}

EnterpriseContext

git地址:https://github.com/yimogit/EnterpriseFrame

文笔有限,就直接贴代码了。记录下自己开发需要到的干货。希望不会误导路过的各位,文中若有误,还望路过的道友指出。

时间: 2024-11-25 12:46:55

个人项目框架搭建 -- 仓储模式使用的相关文章

1、Android项目框架搭建 (分析需求、整理资料)

闲来无事.想搭个框架试试 分析一般应用 将资料整理整理 粗略统计 需要以下资料 1.android-pulltorefresh 一个强大的拉动刷新开源项目,支持各种控件下拉刷新 ListView.ViewPager.WevView.ExpandableListView.GridView.(Horizontal )ScrollView.Fragment上下左右拉动刷新,比下面johannilsson那个只支持ListView的强大的多.并且他实现的下拉刷新ListView在item不足一屏情况下也

(三) Angular2项目框架搭建心得

前言: 在哪看到过angular程序员被React程序员鄙视,略显尴尬,确实Angular挺值得被调侃的,在1.*版本存在的几个性能问题,性能优化的"潜规则"贼多,以及从1.*到2.*版本的面目全非,不过宽容点来看这个强大的框架,升级到ng2肯定是一件好事情,虽然截至目前ng2还存在或多或少需要完善的地方,但是ng2做到了留下并强化ng1好的部分,移除或改善其不好的部分,并且基于许多较新Web技术来开发,不去看从ng1迁移到ng2的门槛和工作量的话,ng2的编程体验是很酷炫的. 目前n

[AngularJS]项目框架搭建-MyFirst Skeleton

前文有提到过 做一个简单的订餐系统,最近花了点时间,了解了一下AngularJS框架的使用.因此本文的目的根据了解的知识重新搭建基于 AngularJS框架. 该框架是基于对于AngularJS的学习而制定的,这其中肯定有很多不足,在以后的学习中在加以改进. 一.系统准备 安装Node.js version>=0.10.0版本 Git  Shell 并添加该 Shell脚本到Path环境变量中  Path=:,"$git_home/bin"   二.手动搭建框架 2.1 创建开发

第一节项目框架搭建

动软代码生成器的使用 创建三个类库项目DAL.BLL.Model,创建两个asp.net应用程序Web:Front(前台).Admin(后台管理).DAL引用Model,BLL引用Model和DAL,Web引用BLL和Model. 如果报错“添加服务器配置失败”,则以管理员身份运行“动软代码生成器”. (*)根据我的表命名规范,配置“动软”的“选项”→“代码生成器设置”,命名规则中“替换表中的字符”填“T_”(大小写敏感),“类命名规则”中,除了Model最后一个文本框留空之外,其他两个填BLL

ASP.NET MVC企业级项目框架搭建实战

MVC项目搭建笔记---- 项目框架采用ASP.NET MVC+Entity Framwork+Spring.Net等技术搭建,搭建过程内容比较多,结合了抽象工厂的思想降低了三层之间的耦合,可以使用此套框架进行可扩展性要求高的企业级MVC项目开发.本框架的架构图如下: 第一步(创建分类文件夹): 创建5个文件夹.分别为UI,Model,BLL,DAL,Common,以便于将各模块分类整理. 第二步(项目类库的创建): 在UI文件夹创建ASP.NET MVC4项目模板选择基本. 在Model文件夹

记录-项目java项目框架搭建的一些问题(maven+spring+springmvc+mybatis)

伴随着项目框架的落成后,本以为启动就能成功的,but.... 项目启动开始报错误1:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener 这个错百度到说是缺少这个包,但实际在项目中看到maven里面是有这个包的.于是继续百度到[可能包是找到了,但没有依赖在项目中] 项目右击-----project-----deployment assembly , add ,java bui

2.0项目框架搭建

2.1.科学减肥网: http://www.kxjf1.com 项目架构如下 解决方案分层 01UI KXJF.Helper(web.wap帮助类库) KXJF.Logic(web控制器逻辑) KXJF.Logic.SysAdmin(web后台控制器逻辑) KXJF.Logic.Wap(wap控制器逻辑) KXJF.UrlProvider(URL优化,提供良好的URL) 02Service KXJF.IBLL(业务逻辑接口层) KXJF.BLL(业务逻辑实现层) 03Repository KXJ

浅谈 WPF 项目框架搭建

在WPF项目开发中最常用的开发模式无疑是MVVM模式,  MVVM模式开发的好处,在这里就不详细讨论, 还有 本文中所使用MVVMLight框架,为什么使用MVVM框架(1.框架较轻,2.学习成本低.3.适用大多数中小型项目,4.相对于微软的prism框架更容易上手)    下面开始 一步一步 搭建框架 第一步: 利用反射创建VM构造器 public class ViewModelFactory { private static Dictionary<string, object> vmMap

springmvc+mybatis+maven项目框架搭建

项目的目录 1.配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com