2017-10-16 14 views
0

我正嘗試使用一個變量訪問不同的上下文。請看看之前的代碼:c#如何製作一個動態的Context,來訪問不同的數據庫?

... 
    private readonly ClientOneType _contextClientOne; 
    private readonly ClientTwoType _contextClientTwo; 

    public ExampleService() 
    { 
     _contextClientOne = new ClientOneType(); 
     _contextClientTwo = new ClientTwoType(); 
    } 

    public Stores[] GetStores(Store storeModel) 
    { 

     try 
     { 
      var _dynamicContext = null; //this throws an error because c# needs a type for runtime. 

      if (client == "OutBack") 
       _dynamicContext = _contextClientOne; 
      else if(client == "DollarGeneral") 
       _dynamicContext = _contextClientTwo; 

      var stores = (from s in _dynamicContext.Store //this is where the magic should take place 
          where s.StoreName == storeModel.StoreName 
          select p).ToArray(); 

      return stores; 
     } 

     ... 
    } 

運行,是因爲_dynamicContext不能爲空,所以我怎樣才能創建一個可改變成不同的上下文變量時我得到一個錯誤?

懶惰的解決方案是爲每個客戶端創建不同的方法,但這不會很有效,因爲它將變得無法維護。

我真的很感謝幫助。先謝謝你。

回答

0
public interface IClientType 
{ 
    public Store Store { get; } 
} 

public class ClientOneType : IClientType 
{ 
    ... 
} 

public class ClientTwoType : IClientType 
{ 
    ... 
} 

public Stores[] GetStores(Store storeModel) 
{ 
    try 
    { 
     IClientType _dynamicContext = null; 
     ... 
0

ClientOneType和ClientTwoType是否都從暴露名爲「Store」的屬性的基類中驅動?
我猜他們沒有,因爲他們沒有,沒有辦法使用相同的變量來寫你正在編寫的LINQ查詢,因爲編譯器必須能夠確定哪些屬性可用。

但是,你可以使用IQueryable的動態構建查詢

IQueryable<Stores> storeQry=null; 

if (client == "Walmart") 
    storeQry= _contextClientOne.Store.AsQueryable();    
else if(client == "CHS") 
    storeQry= _contextClientTwo.Store.AsQueryable(); 

var stores = (from s in storeQry 
      where s.StoreName == storeModel.StoreName 
      select p).ToArray(); 
+0

爲我工作很好,非常感謝你。 – RDevAwe

相關問題