2009-06-30 48 views
1

在ASP.NET MVC中的非Linq2Sql模型绑定示例我注意到很多ASP.NET的例子使用Linq2Sql作为数据源的ASP.NET MVC

是否有任何示例可以显示如何使用非Linq2Sql数据源(即数据集)或(基于自定义业务对象的)通用列表/项目集合进行模型绑定?即

public class WebsiteList : List<Website> 
{ 
    public WebsiteList() 
    { 
    } 
} 

ASP.NET MVC是伟大的,尤其是它的“使用任何你想要的”方法。使用Linq2Sql的例子太多了,真让人遗憾。

回答

2

很多可以通过用您自己的自定义存储库替换Linq2Sql部件来使用的示例。由于它是IQueryable,因此可以用“WebsiteList.AsQueryable()”替换它,并按原样使用大部分示例。举例来说,这里是一个虚拟存储库使用:

public class FakeRepository<T> : IResourceRepository<T> where T : class 
{ 
    private readonly List<T> items = new List<T>(); 
    private readonly IObjectFactory resolver; 

    public FakeRepository(IObjectFactory resolver) 
    { 
     this.resolver = resolver; 
    } 

    public IQueryable<T> GetAll() 
    { 
     return this.items.AsQueryable(); 
    } 

    public void Save(T item) 
    { 
     if (!this.items.Contains(item)) 
     { 
      this.items.Add(item); 
     } 
    } 

    public void Delete(T item) 
    { 
     this.items.Remove(item); 
    } 

    public T Create() 
    { 
     return this.resolver.GetInstance<T>(); 
    } 
} 

我可以用实际存储库(可能是LINQ2SQL,ADO.NET实体,亚音速,...)轻松地交换了这一点。

0

Linq to SQL将获取数据库表并将它们映射到业务类。要在没有Linq to SQL的情况下执行相同的操作,只需手动建模数据类,并包含代码以读取并保存到数据库。

namespace MyProject.Model 
{ 
    public class Website 
    { 
     public int WebsiteID { get; set } 
     public string Name { get; set } 
     public string Url { get; set } 
     public string Author { get; set } 
    } 

    public class WebsiteRepository 
    { 
     public Website Read(int id) { // read from database } 
     public void Write(Website website) { // write to database } 
     public website[] GetWebsites { } 
    } 
} 

namespace MyProject.Controllers 
{ 
    public class WebsiteController 
    { 
     WebsiteRepository repository = new WebsiteRepository(); 

     ActionResult Index() 
     { 
      Website[] websites = repository.GetWebsites(); 
      return View(websites); 
     } 
    } 
} 
+0

我这样做〜〜LINQ到SQL也是如此。我不喜欢我的代码库其余部分与LINQ生成的类紧密绑定,因此它们在我创建的POCOs之间进行了转换。 – mmcdole 2009-06-30 03:47:06