当用户访问www.yoursite.com/Products/Index时,我们希望显示产品的名称,分类、数量、单价和折扣。因此我们需要使用NorthwindDataContext这个辅助类,它是由Linq-to-SQL工具自动产生的一个类,辅助我们对数据库的存取。因为我们要在控制器的所有action方法中都要用到这个辅助类,因此可以增加一个叫DataContext的属性去返回这个类的实例。此外,这个属性将对NorthwindDataContext实例进行一些属性的设置,以实现在加载产品的时候同步加载产品所属的目录(注意:Linq-to-SQL默认是使用延迟加载的,所谓的延迟加载,就是比如我们在显示每个产品的时候,并不希望ORM框架同步加载产品所属的分类,因为同步加载的话当数据量大的时候是会很耗费资源的)。代码实现如下:
public class ProductsController : Controller
{
private NorthwindDataContext _DataContext = null;
protected NorthwindDataContext DataContext
{
get
{
if (_DataContext == null)
_DataContext = new NorthwindDataContext();
// Eager load Category info
var options = new DataLoadOptions();
options.LoadWith(p => p.Category);
_DataContext.LoadOptions = options;
return _DataContext;
}
}
// GET: /Products/
public ActionResult Index()
{
return View();
}
}
{
private NorthwindDataContext _DataContext = null;
protected NorthwindDataContext DataContext
{
get
{
if (_DataContext == null)
_DataContext = new NorthwindDataContext();
// Eager load Category info
var options = new DataLoadOptions();
options.LoadWith(p => p.Category);
_DataContext.LoadOptions = options;
return _DataContext;
}
}
// GET: /Products/
public ActionResult Index()
{
return View();
}
}
控制器实际的工作是两件事:接受用户的请求,访问数据库并将返回的数据决定用什么视图去返回给用户。我们这里仅是简单去对实体模型Product进行ORM操作,因此只需要如下代码就可以访问数据库的Product表了:
var model = this.DataContext.Products;
但如何将结果返回给视图呢?控制器有两种方法返回结果给视图:通过弱类型的ViewData集合或使用强类型的视图。我们这里使用的是后一种方法:
public class ProductsController : Controller
{
...
// GET: /Products/
public ActionResult Index()
{
var model = this.DataContext.Products;
return View(model);
}
}
{
...
// GET: /Products/
public ActionResult Index()
{
var model = this.DataContext.Products;
return View(model);
}
}
看到了么?这里我们直接将model作为参数传递给View层了。