2016-07-04 29 views
0

我創建了一個通用下拉列表在我的控制器使用方法:倉庫作爲參數

GenericDropDownList("myDropDown"); 

    private void GenericDropDownList(string dropdownName, object selectedDepartment = null) { 

    var dropdownQuery = unitOfWork.SalesRepository.Get(orderBy: q => q.OrderBy(d => d.FirstName)); 

    ViewData[dropdownName] = new SelectList(dropdownQuery, "LastName", "LastName", selectedDepartment); 
    } 

這似乎很好地工作。我想要是讓unitOfWork.TestRepository動態,這樣我就可以在函數中使用所有可用的資源庫:

GenericDropDownList("myDropDown", SalesRepository); 

    private void GenericDropDownList(string dropdownName, object repository, object selectedDepartment = null) { 

    var dropdownQuery = repository.Get(orderBy: q => q.OrderBy(d => d.FirstName)); 

    ViewData[dropdownName] = new SelectList(dropdownQuery, "LastName", "LastName", selectedDepartment); 
    } 

以上不起作用。我收到以下錯誤:

Error CS1061 'object' does not contain a definition for 'Get' and no extension method 'Get' accepting a first argument of type 'object' could be found

是否可以使下拉按照我想要的那樣動態變化?

回答

0

object沒有.Get方法,所以這是不合理的。

使用dynamic會解決這個問題,因爲那時.Get在運行時解決,雖然在性能成本,並與一個運行時錯誤的風險,如果.Get在運行時不存在。

在我看來,最好的方法是使用一個接口:通過使用部分類

private void GenericDropDownList(string dropdownName, IRepository repository, object selectedDepartment = null) 
{ 
    // ... 
} 

當使用實體框架可以並處在倉庫類這個接口:

public partial class ThisRepository : IRepository 
{ 
} 

public partial class ThatRepository : IRepository 
{ 
} 

的catch將是一個接口可以而不是定義一個屬性,如FirstName,所以你必須爲此定義一個方法,或使用Func<IRepository, string>爲排序位。

0

如果您想要動態對象,請使用dynamic類型。

或者嘗試強制轉換爲適當的類型:

(repository as type).Get(...) 
0

正確的做法是把所有的資源庫實現與常用方法的通用接口。

例如,您可以創建接口IRepositoryIRepository<TSource>,如果您希望它更具體。

問題是根據您的預期代碼TSource應具有FirstName屬性。

您確定所有的存儲庫都有FirstName屬性的實體嗎?

如果答案是沒有,那麼你就不能創造這樣的泛型方法(你需要重新定義你的邏輯,或創建一個特定的接口,將有實體與此屬性,但你不能通過任何存儲庫,只有實現此接口的那些)。

如果答案是肯定的,那麼你就可以創建你的所有源實體基類BaseEntity,例如),這將有FirstName財產。

假如答案是肯定的,那麼你就可以在你的方法的簽名改爲:

private void GenericDropDownList(string dropdownName, IRepository<TSource> repository, object selectedDepartment = null) where TSource : BaseEntity 

你會那麼可以把它叫做:

GenericDropDownList("myDropDown", SalesRepository); //SalesRepository should implement IRepository<Sale>, where Sale : BaseEntity