我問一個關於ASP.NET MVC的通用控制器和this answer問題表示控制器是這樣的:如何使用ASP.NET MVC的通用控制器來填充正確的模式
public abstract class GenericController<T> where T : class { public virtual ActionResult Details(int id) { var model = _repository.Set<T>().Find(id); return View(model); } }
這可以這樣實現的。
public class FooController : GenericController<Foo> { }
現在,當有人請求/美孚/詳細信息/ 42,entitiy從_repository的
Set<Foo>()
拉,而無需編寫的,在任何FooController
。
他解釋說,是好的,但覺得我要開發的產品和客戶的通用控制器,在那裏我不會用EF加載產品&客戶模式,而使用MS數據訪問應用程序塊的方式。
public abstract class GenericController<T>
where T : class
{
public virtual ActionResult Details(int id)
{
//var model = _repository.Set<T>().Find(id);
var model =customer.load(id);
or
var model =product.load(id);
return View(model);
}
}
所以,當收到請求時喜歡/Customer/Details/42 or /product/Details/11
那麼通用控制器的詳細方法將調用,但我們如何能夠檢測請求來自哪個控制器和相應的實例正確的類加載正確的模式。
如果客戶有要求,那麼我需要從詳細的操作方法中加載客戶詳細信息,或者如果請求來自產品,那麼我需要從通用控制器的詳細操作方法加載產品詳細信息。
如何使用泛型來獲取帶有實體框架數據塊的T
類型的數據集?
通用控制器的目標是什麼? –
您需要在當前工作的控制器中顯示初始化數據塊的代碼。泛型的東西是,你不能按照它的類型訪問模型;你讓你的倉庫返回它。這就是你可以使用實體框架的'DbContext.Set()'方法,所以你的通用控制器_不會在編譯時知道它將返回哪個具體模型。我們可以給出一個數據塊的例子,但是如果你顯示你當前的代碼,這樣做是最簡單的。 –
CodeCaster