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

 

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

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

IRepository.cs代码:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

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

        /// 
        /// Gets a table
        /// 
        IQueryable Table { get; }
        /// 
        /// IRespository插入接口
        /// 
        /// 
        /// 
        bool InsertEntity(T entity);


        /// 
        /// IRespository修改接口
        /// 
        /// 
        /// 
        bool UpdateEntity(T entity);

        /// 
        /// IRespository删除
        /// 
        /// 
        /// 
        bool DeleteEntity(T entity);

        /// 
        /// 根据id查询
        /// 
        /// 
        /// 
        T GetEntityById(object Id);

        /// 
        /// 带条件查询
        /// 
        /// 
        /// 
        T Get(Expression> where);


        /// 
        /// 查询所有
        /// 
        /// 
        IEnumerable GetALLEntity();

        /// 
        /// 这里也可以用IEnumerable类型,带条件查询所有
        /// 
        /// 
        /// 
        IQueryable GetAllEntityWhere(Expression> where);


        /// 
        /// 分页
        /// 
        /// 
        /// 
        /// 
        IList GetPageEntities(int pageIndex, int PageSize);

        /// 
        /// 分页带查询条件
        /// 
        /// 
        /// 
        /// 
        /// 
        IList GetPageEntities(int pageIndex, int PageSize, Expression> where);



    }
}
复制代码

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 : IRepository where T : class
    {

        private readonly IDbContext _context;
        private IDbSet _entities;

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

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

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

        }


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

        }

        /// 
        /// 删除实体
        /// 
        /// 
        /// 
        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;

        }

        /// 
        /// 对Set根据id 的查询的操作
        /// 
        /// 
        /// 
        public T GetEntityById(object Id)
        {
            return this.Entities.Find(Id);
        }

        /// 
        /// 这里对Set是带条件的操作
        /// 
        /// 
        /// 
        public T Get(Expression> where)
        {
            return this.Entities.Where(where).FirstOrDefault();
        }



        /// 
        /// 查询所有的
        /// 
        /// 
        public IEnumerable GetALLEntity()
        {
            //  throw new NotImplementedException();

            IEnumerable query = this.Entities;

            return query;
        }

        /// 
        /// 查询所有带条件
        /// 
        /// 
        /// 
        public IQueryable GetAllEntityWhere(Expression> where)
        {
            IQueryable query = this.Entities.Where(where);
            return query;

        }


        /// 
        /// 分页方法
        /// 
        /// 
        /// 
        /// 
        public IList GetPageEntities(int pageIndex, int PageSize)
        {
            IList List = this.Entities.Skip(pageIndex * PageSize).Take(PageSize).ToList();
            return List;

        }


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

        }



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

        }
    }
}
复制代码

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
    {
        /// 
        /// Get DbSet
        /// 
        /// Entity type
        /// DbSet
        IDbSet Set() where TEntity : class;

        /// 
        /// Save changes
        /// 
        /// 
        int SaveChanges();

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

        /// 
        /// 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.
        /// 
        /// The type of object returned by the query.
        /// The SQL query string.
        /// The parameters to apply to the SQL query string.
        /// Result
        IEnumerable SqlQuery(string sql, params object[] parameters);

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

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 Admins { get; set; }
        public virtual DbSet ArticleInfoes { get; set; }
        public virtual DbSet ArticleRelations { get; set; }
        public virtual DbSet ArticleTypes { get; set; }
        public virtual DbSet FriendsLinks { get; set; }
        public virtual DbSet Permissions { get; set; }
        public virtual DbSet Role_Permission { get; set; }
        public virtual DbSet Roles { get; set; }
        public virtual DbSet SiteALlConfigs { get; set; }
        public virtual DbSet 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()
                .Property(e => e.ArtContent)
                .IsUnicode(false);


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

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

            base.OnModelCreating(modelBuilder);
        }
        #endregion

        #region Methods

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

        /// 
        /// Get DbSet
        /// 
        /// Entity type
        /// DbSet
        public new IDbSet Set() where TEntity : class
        {
            return base.Set();
        }

        /// 
        /// Execute stores procedure and load a list of entities at the end
        /// 
        /// Entity type
        /// Command text
        /// Parameters
        /// Entities
        public IList ExecuteStoredProcedureList(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(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;
        }

        /// 
        /// 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.
        /// 
        /// The type of object returned by the query.
        /// The SQL query string.
        /// The parameters to apply to the SQL query string.
        /// Result
        public IEnumerable SqlQuery(string sql, params object[] parameters)
        {
            return this.Database.SqlQuery(sql, parameters);
        }

        /// 
        /// Executes the given DDL/DML command against the database.
        /// 
        /// The command string
        /// false - the transaction creation is not ensured; true - the transaction creation is ensured.
        /// Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used
        /// The parameters to apply to the command string.
        /// The result returned by the database after executing the command.
        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
    }
}
复制代码

转载于:https://www.cnblogs.com/zzp0320/p/7909547.html

你可能感兴趣的:(个人项目框架搭建--仓储模式使用)