一歩一歩ASPを作成する.NET MVC 5プログラム[Repository+Autofac+Automapper+SqlSugar](六)


前言


こんにちは、レコードです
また金曜日、ワクワクして、嬉しくて、盛り上がって...やれやれ...レコードはコード友网でまたみんなに会いました!!!下一篇《一歩一歩ASP.NET MVC 5プログラムを作成する[Repository+Autofac+Automapper+SqlSugar](五)》を完成しました.
  • AutoMapperの概要
  • AutoMapper
  • をインストール
  • AutoMapperの構成
  • AutoMapperのアプリケーション
  • 前の記事の学習を通して、本シリーズの「一歩一歩ASP.NET MVC 5プログラムを作成する[Repository+Autofac+Automapper+SqlSugar]」で主に関連する技術とコンポーネントを基本的に紹介しました.次のシリーズの文章は主に知識技術の統合、向上、再構築などを中心に展開し、プロジェクトの実戦で出会った様々な問題を解決することで、みんなが目を持って、方向性を持って勉強することを助け、みんなのASPを向上させる.NENT MVC 5開発スキルの効果.

    本文の知識の要点


    今日皆さんにお伝えしたいのは、このシリーズ[ASP.NET MVC 5プログラムを一歩一歩作成する]のステップアップの知識です.
  • 汎用倉庫
  • なぜ汎用倉庫を使うのか


    なぜ汎用倉庫を使用するのかというと、私たちは私たちのプロジェクトに戻って、プロジェクト設計で駆動しなければなりません.なぜ汎用倉庫なのか、汎用倉庫でどのようなメリットがあるのかを説明します.

    プロジェクト自体に戻る


    v 1.5バージョンでは、倉庫層とサービス層を実現しました.ここで、倉庫層は私たちが直接データベースにアクセスする層であり、倉庫層を通じてデータベースに対して任意の権限のある操作を行うことができ、増加、削除、変更、調査を含む.私たちのPostRepossitory博文倉庫実装クラスはすでにそのインタフェースの増加、削除、変更、検索操作、IPostRepossitoryインタフェースを実現しています.
    using System.Collections.Generic;
    using TsBlog.Domain.Entities;
    
    namespace TsBlog.Repositories
    {
        public interface IPostRepository
        {
            /// 
            ///   ID      
            /// 
            /// ID
            /// 
            Post FindById(int id);
            /// 
            ///       (   ,       )
            /// 
            /// 
            IEnumerable FindAll();
    
            /// 
            ///       
            /// 
            ///      
            /// 
            int Insert(Post entity);
    
            /// 
            ///       
            /// 
            ///      
            /// 
            bool Update(Post entity);
    
            /// 
            ///           
            /// 
            ///      
            /// 
            bool Delete(Post entity);
    
            /// 
            ///     ID   
            /// 
            ///   ID
            /// 
            bool DeleteById(object id);
    
            /// 
            ///     ID     (    )
            /// 
            ///   ID  
            /// 
            bool DeleteByIds(object[] ids);
        }
    }

    このインタフェースクラスファイルを見て、データベースにユーザーテーブル(User)を追加し、レルムプロジェクト(TsBlog.Domain)でレルムエンティティ(User)を作成する場合、このシリーズの前に倉庫とサービス層インタフェースを追加する手順に従って、倉庫にIUserRepositoryを作成する必要があるかどうかを考えてみましょう.cs、IUserRepositoryにも追加、削除、変更、検索方法が含まれている場合は、IPostRepositoryのすべてのインタフェースメソッドをIUserRepositoryにコピーする必要がありますか?csファイルは?同時に、その実装も同様にコピーされます.
    もし私たちがまたデータベースに複数のテーブルを追加したら、対応する倉庫インタフェースと実現はまた以上の操作を繰り返すのではないでしょうか.ctrl+c , ctrl+v !!! もしそうなら、コードジェネレータを使うほうが速いです.
    ここを見て、開発経験のある開発者たちに冗談を言わないでほしい.当初筆者は初入したことを思い出す.NET開発の時もそうでしたが、コピー、貼り付け、コードジェネレータも使っていました.時間と経験の蓄積に従って、あなたももっと良くなって、前提は少なく使うか、コピーしないで、貼り付けて符号化機能を実現することで、ネット上で探した実現方法でも、自分で叩いてみなければなりません.
    以上の2つの話は問題を逃して、私たちはやはり本題に戻って、上述の問題は実は繰り返しの仕事を避ける方法があって、私たちの仕事量を軽減することができて、つまり汎用的な倉庫を使用します.

    汎用倉庫の実現


    まず、プロジェクト[TsBlog.Repositories]を開き、インタフェースファイルIrepositorryを作成します.cs、共通のクエリーインタフェースメソッドを記述します.
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    
    namespace TsBlog.Repositories
    {
        /// 
        ///        
        /// 
        ///      
        public interface IRepository where T : class, new()
        {
            /// 
            ///           
            /// 
            ///    
            ///     
            T FindById(object pkValue);
    
            /// 
            ///       (   ,   )
            /// 
            /// 
            IEnumerable FindAll();
            /// 
            ///         
            /// 
            ///       
            ///   
            ///       
            IEnumerable FindListByClause(Expression> predicate, string orderBy);
    
            /// 
            ///         
            /// 
            ///       
            /// 
            T FindByClause(Expression> predicate);
    
            /// 
            ///       
            /// 
            ///    
            /// 
            long Insert(T entity);
    
            /// 
            ///       
            /// 
            /// 
            /// 
            bool Update(T entity);
    
            /// 
            ///     
            /// 
            ///    
            /// 
            bool Delete(T entity);
            /// 
            ///     
            /// 
            ///     
            /// 
            bool Delete(Expression> @where);
    
            /// 
            ///     ID   
            /// 
            /// 
            /// 
            bool DeleteById(object id);
    
            /// 
            ///     ID     (    )
            /// 
            /// 
            /// 
            bool DeleteByIds(object[] ids);
        }
    }

    汎用ベースクラスの作成cs :
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    
    namespace TsBlog.Repositories
    {
        public abstract class GenericRepository : IRepository where T : class, new()
        {
            #region Implementation of IRepository
    
            /// 
            ///           
            /// 
            ///    
            ///     
            public T FindById(object pkValue)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var entity = db.Queryable().InSingle(pkValue);
                    return entity;
                }
            }
    
            /// 
            ///       (   ,   )
            /// 
            /// 
            public IEnumerable FindAll()
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var list = db.Queryable().ToList();
                    return list;
                }
            }
    
            /// 
            ///         
            /// 
            ///       
            ///   
            ///       
            public IEnumerable FindListByClause(Expression> predicate, string orderBy)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var entities = db.Queryable().Where(predicate).ToList();
                    return entities;
                }
            }
    
            /// 
            ///         
            /// 
            ///       
            /// 
            public T FindByClause(Expression> predicate)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var entity = db.Queryable().First(predicate);
                    return entity;
                }
            }
    
            /// 
            ///       
            /// 
            ///    
            /// 
            public long Insert(T entity)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    //            
                    var i = db.Insertable(entity).ExecuteReturnBigIdentity();
                    return i;
                }
            }
    
            /// 
            ///       
            /// 
            /// 
            /// 
            public bool Update(T entity)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    //           
                    var i = db.Updateable(entity).ExecuteCommand();
                    return i > 0;
                }
            }
    
            /// 
            ///     
            /// 
            ///    
            /// 
            public bool Delete(T entity)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var i = db.Deleteable(entity).ExecuteCommand();
                    return i > 0;
                }
            }
    
            /// 
            ///     
            /// 
            ///     
            /// 
            public bool Delete(Expression> @where)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var i = db.Deleteable(@where).ExecuteCommand();
                    return i > 0;
                }
            }
    
            /// 
            ///     ID   
            /// 
            /// 
            /// 
            public bool DeleteById(object id)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var i = db.Deleteable(id).ExecuteCommand();
                    return i > 0;
                }
            }
    
            /// 
            ///     ID     (    )
            /// 
            /// 
            /// 
            public bool DeleteByIds(object[] ids)
            {
                using (var db = DbFactory.GetSqlSugarClient())
                {
                    var i = db.Deleteable().In(ids).ExecuteCommand();
                    return i > 0;
                }
            }
    
            #endregion
        }
    }

    現在、倉庫インタフェースと汎用倉庫ベースクラスが作成されています.次に、IPostRepositoryとPostRepossitoryを再構築し、IrepositoryとGenericRepossitoryからそれぞれ継承させます.
    IPostRepository.cs
    using TsBlog.Domain.Entities;
    
    namespace TsBlog.Repositories
    {
        public interface IPostRepository :IRepository
        {
    
        }
    }

    PostRepository.cs
    using TsBlog.Domain.Entities;
    
    namespace TsBlog.Repositories
    {
        /// 
        /// POST        
        /// 
        public class PostRepository : GenericRepository
        {
           
        }
    }

    IPostRepositoryとPostRepositoryは簡単になったのではないでしょうか.しかし、実現方法は再構築前と同じです.
    どのようにして、ユーザーテーブルの倉庫インタフェースと倉庫の実現を追加すれば、非常に簡単ではないでしょうか.繰り返しの増加、削除、変更、検索操作のためにコピーしたり、貼り付けたりする必要はありません.

    インタフェースベースの依存注入の構成


    プロジェクト【TsBlog.Repositories】にインタフェースクラスIDependencyを追加する.cs :
    namespace TsBlog.Repositories
    {
        /// 
        ///          
        /// 
        public interface IDependency
        {
        }
    }

    汎用倉庫における抽象ベースクラスGenericRepository.csにIDependencyインタフェース制約を追加するには:
    public abstract class GenericRepository : IDependency, IRepository where T : class, new()

    プロジェクト[TsBlog.Frontend]のGlobalを開きます.asax AutofacRegisterメソッドを再構成するには、次の手順に従います.
    private void AutofacRegister()
    {
        var builder = new ContainerBuilder();
    
        //  MvcApplication          
        builder.RegisterControllers(typeof(MvcApplication).Assembly);
    
        //       
        //builder.RegisterType().As();
        
        //           
        var assembly = AppDomain.CurrentDomain.GetAssemblies();
        builder.RegisterAssemblyTypes(assembly)
            .Where(
                t => t.GetInterfaces()
                    .Any(i => i.IsAssignableFrom(typeof(IDependency)))
            )
            .AsImplementedInterfaces()
            .InstancePerDependency();
        
        //       
        builder.RegisterType().As();
    
        //     
        builder.RegisterFilterProvider();
    
        var container = builder.Build();
    
        //         
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

    F 5で運転していますが、間違っていませんか?はい、私たちはさっき汎用倉庫のInsertの戻りタイプを修正したので、IPostServicesを修正しました.csのInsertの戻りタイプはlongです.
    long Insert(Post entity);

    修正後のIPostServices.cs:
    using System.Collections.Generic;
    using TsBlog.Domain.Entities;
    
    namespace TsBlog.Services
    {
        public interface IPostService
        {
            /// 
            ///   ID      
            /// 
            /// ID
            /// 
            Post FindById(int id);
            /// 
            ///       (   ,       )
            /// 
            /// 
            IEnumerable FindAll();
    
            /// 
            ///       
            /// 
            ///      
            /// 
            long Insert(Post entity);
    
            /// 
            ///       
            /// 
            ///      
            /// 
            bool Update(Post entity);
    
            /// 
            ///           
            /// 
            ///      
            /// 
            bool Delete(Post entity);
    
            /// 
            ///     ID   
            /// 
            ///   ID
            /// 
            bool DeleteById(object id);
    
            /// 
            ///     ID     (    )
            /// 
            ///   ID  
            /// 
            bool DeleteByIds(object[] ids);
        }
    }

    PostServicesを変更します.csのInsertの戻りタイプはlongです.
    public long Insert(Post entity)
    {
          return _postRepository.Insert(entity);
    }

    修正後のPostServices.cs:
    using System.Collections.Generic;
    using TsBlog.Domain.Entities;
    using TsBlog.Repositories;
    
    namespace TsBlog.Services
    {
        public class PostService : IPostService
        {
            private readonly IRepository _postRepository;
            public PostService(IRepository postRepository)
            {
                _postRepository = postRepository;
            }
            public bool Delete(Post entity)
            {
                return _postRepository.Delete(entity);
            }
    
            public bool DeleteById(object id)
            {
                return _postRepository.DeleteById(id);
            }
    
            public bool DeleteByIds(object[] ids)
            {
                return _postRepository.DeleteByIds(ids);
            }
    
            public IEnumerable FindAll()
            {
                return _postRepository.FindAll();
            }
    
            public Post FindById(int id)
            {
                return _postRepository.FindById(id);
            }
    
            public long Insert(Post entity)
            {
                return _postRepository.Insert(entity);
            }
    
            public bool Update(Post entity)
            {
                return _postRepository.Update(entity);
            }
        }
    }

    注意:PostRepository.csではまだIPostRepositoryに継承されていません。cs、だからPostServices.csのコンストラクション関数では、汎用インタフェースIrepositoryを一時的に使用します。 private readonly IRepository _postRepository; public PostService(IRepository postRepository)
    _postRepository = postRepository;

    }
              
    
    
       F5  ,    [http://localhost:54739/home/post],         ,  。。。
    
    ![create-aspnet-mvc-5-web-application-repository-autofac-automapper-sqlsugar-step-by-step-06][2]
    
             :https://github.com/lampo1024/TsBlog/releases/tag/v1.6
    
            ,       ,      ……
    
         Rector      ,         。
    
    
         [   ][3] 《[      ASP.NET MVC5  \[Repository+Autofac+Automapper+SqlSugar\]( )][4]》
    
    
      [1]: http://codedefault.com/p/create-aspnet-mvc-5-web-application-repository-autofac-automapper-sqlsugar-step-by-step-05
      [2]: http://statics.codedefault.com/uploads/2017/12/create-aspnet-mvc-5-web-application-repository-autofac-automapper-sqlsugar-step-by-step-05-05.png
      [3]: http://codedefault.com