1

이 두 링크를 사용하여 Repo, 작업 단위, EF, DI로 프로젝트를 구현했습니다. http://www.codeproject.com/Articles/838097/CRUD-Operations-Using-the-Generic-Repository-Pat 다중 Db로 작업하기. 다른 DB에 연결된 DbContexts를 주입하는 방법은 무엇입니까?

그러나 때문에 기존 데이터베이스 잠시 후 http://www.codeproject.com/Articles/814768/CRUD-Operations-Using-the-Generic-Repository-Patte

    1. , 나는 두 개의 데이터베이스 내 사업을 확장했다. 그러나 지금까지는 두 개의 데이터베이스로 작업 할 수 있도록 프로젝트를 확장 할 수 없었습니다. 누구나 언급 된 링크를 기반으로 여러 데이터베이스 작업에 관한 솔루션을 제공 해주시겠습니까?

      미리 감사드립니다.

      업데이트

      코어

      **Financial Database** 
      
      public class Vou : Entity 
          { 
          public Nullable<long> Num { get; set; } 
          public string Subj { get; set; } 
          } 
      
          **Trading Database** 
      
      public class Goods : Entity 
          { 
          public long Code { get; set; } 
          public string Title { get; set; } 
          } 
      

      데이터

      public interface IDbContext 
          { 
           IDbSet<TEntity> Set<TEntity>() where TEntity : Entity; 
           int SaveChanges(); 
          } 
      
      
      public class IocDbContext : DbContext, IDbContext 
          { 
           public IocDbContext() 
            : base("name=FinancialEntities") 
           { 
           } 
      
           public new IDbSet<TEntity> Set<TEntity>() where TEntity : Entity 
           { 
            return base.Set<TEntity>(); 
           } 
          } 
      
      
      public interface IRepository< TEntity> 
          { 
           TEntity Get(int id); 
          } 
      
      
      
      public class Repository<T> : IRepository<T> where T : Entity 
          { 
           protected readonly DbContext context; 
           private IDbSet<T> _entities; 
      
           public Repository(IocDbContext context) 
           { 
            this.context = context; 
           } 
      
           public void Save() 
           { 
            this.context.SaveChanges(); 
           } 
      } 
      
  • 답변

    0

    여러 데이터베이스 dbContext 당 연결을 의미한다. 두 기사에서 DbContext는 다음과 같이 생성됩니다 :

    public EFDbContext() 
         : base("name=DbConnectionString") 
        { 
        } 
    

    을 다음 레 포스의의 ctor에서 :

    public EFDvContext (DbConnection connection) 
         : base(connection, true) 
        { 
    
        } 
    

    및 패스 : 당신이 필요로하는 것은이 같은 EFDvContext의 다른 ctor에이

    public Repository(EFDbContext context) 
        { 
         this.context = context; 
        } 
    

    입니다 다음과 같이 Repo에 있습니다.

    public Repository(IDbContextProvider contextProvider) 
        { 
         this._contextProvider = contextProvider; 
        } 
    
    당신은 당신이 순서 특정 DB 연결을 생성에 필요한 논리를 넣을 수 있습니다

    public interface IDbContextProvider 
        { 
         DbContext Current(); 
         DbContext Specified(string dbName); 
        } 
    

    및 IDbContextProvider의 구현 내부 :210

    는 당신은 IDbContextProvider과 같이해야합니다. 나는 잘 작동하는 여러 개의 db`s에 대해 이러한 구현을 사용합니다.

    경험 법칙 : "다른 수준의 간접 참조가 필요할 때 다른 수준의 추상화가 필요합니다."

    경우에 따라 단일 수준이 아닌 여러 수준의 간접 참조가 필요합니다. 따라서 선택 (간접 지정)은 연결 수준에서 증가합니다. 따라서 그 시점에서 다른 수준의 추상화가 필요합니다. 즉, 다른 연결을 얻을 수있는 것입니다.

    업데이트의 여기 조인 경우 는 일부 내 구현하지만 당신은 너무 다른 here를 찾을 수 있습니다. 비슷한 질문이 있습니다. 검색 만하면됩니다.

    entities = _myEntityRepository.GetOne(includeProperties:new Expression<Func<MyEntity, object>>[] 
          { 
           x => x.AnotherEntity1, 
           x => x.AnotherEntity2, 
           x => x.AnotherEntity3, 
          }); 
    

    내가 된 IQueryable 내가 '가입'절 결과를 보강 할 수 있습니다 반환하는 방법이 있기 때문에 여기

    public virtual IEnumerable<T> GetAll(Expression<Func<T, bool>> where = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, Expression<Func<T, object>>[] includeProperties = null) 
        { 
         return GetAllAsQueryable(where, orderBy, includeProperties).ToArray(); 
        } 
    
        public virtual IQueryable<T> GetAllAsQueryable(Expression<Func<T, bool>> where = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, Expression<Func<T, object>>[] includeProperties = null) 
        { 
         var set = SetWithIncludes(includeProperties); 
         if (where != null) 
         { 
          set = set.Where(where); 
         } 
         return orderBy != null ? orderBy(set) : set; 
        } 
    
        protected IQueryable<T> SetWithIncludes(IEnumerable<Expression<Func<T, object>>> includes) 
        { 
         IQueryable<T> set = DbSet; 
    
         if (includes != null) 
         { 
          foreach (var include in includes) 
          { 
           set = set.Include(include); 
          } 
         } 
    
         return set; 
        } 
    

    그리고 내가 그것을 사용하는 방법입니다. 예 : here 및 그물 주변. 한 가지 기억해야 할 점은 리포지토리를 삭제하고 실행되지 않은 쿼리를 반환하면 '개체 컨텍스트 삭제 예외'와 같은 것을 얻을 수 있기 때문에 리포지토리와 동일한 범위에서 쿼리를 사용해야한다는 것입니다. DbContext 생성 위의 예에서

    private static DbContextAdapter DbContextAdapterFactoryMethod(IKernel k, ComponentModel cm, CreationContext c) 
        { 
         IEfLogger logger = k.Resolve<IEfLogger>(); 
         if (c.HasAdditionalArguments) 
         { 
          IDbModel model = (IDbModel)c.AdditionalArguments["model"]; 
          IDbConnection connection = (IDbConnection)c.AdditionalArguments["connection"]; 
          return DbContextAdapter.CreateCompanyContext(model, connection, logger); 
         } 
         else 
         { 
          return DbContextAdapter.CreateMainContext(logger); 
         } 
        } 
    

    가 파라미터에 의해 구동된다 :

    UPDATE 여기 윈저 성을 갖는 예이다. 기본 생성자가 없습니다.

    +0

    시간과 노력에 감사드립니다. 그러나 솔직히 말해서 나는 당신의 요점을 깨닫지 못했습니다. 또한 당신이 의미하는 경우, 나는 저장소에 컨텍스트를 전달한다. 다른 데이터베이스의 두 테이블 사이에 조인이있을 경우 어떻게해야 하는가? 제게 좀 더 명확하게 설명해 주시겠습니까? – Alex

    +0

    도움을 주신 데 대해 감사드립니다. 하지만 실제로 나는 더 혼란스러워합니다. 내 질문을 내 코드로 업데이트했습니다. "거래 데이터베이스"와 함께 작업 할 수 있도록 조언을 기반으로 코드를 수정하십시오. – Alex

    +0

    어떤 IoC를 사용하십니까? –

    관련 문제