C# ASP.NET MVC中的非Linq2Sql模型绑定示例

C# ASP.NET MVC中的非Linq2Sql模型绑定示例,c#,asp.net-mvc,data-binding,model,C#,Asp.net Mvc,Data Binding,Model,我注意到许多ASP.NET示例都使用Linq2Sql作为数据源 是否有任何示例显示如何将模型绑定与非Linq2Sql数据源(即数据集)或基于自定义业务对象的项的通用列表/集合一起使用?i、 e public class WebsiteList : List<Website> { public WebsiteList() { } } 公共类网站列表:列表 { 公共网站列表() { } } ASP.NETMVC非常棒,尤其是它的“随心所欲”方法。太多的

我注意到许多ASP.NET示例都使用Linq2Sql作为数据源

是否有任何示例显示如何将模型绑定与非Linq2Sql数据源(即数据集)或基于自定义业务对象的项的通用列表/集合一起使用?i、 e

public class WebsiteList : List<Website>
{
    public WebsiteList()
    {
    }  
}
公共类网站列表:列表
{
公共网站列表()
{
}  
}

ASP.NETMVC非常棒,尤其是它的“随心所欲”方法。太多的示例都在使用Linq2Sql,这真是太遗憾了。

Linq to SQL获取您的数据库表并将它们映射到业务类。要在没有LINQtoSQL的情况下完成同样的工作,只需手动建模数据类,并包含从数据库读取和保存到数据库的代码

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);
        }
    }
}

通过使用您自己的自定义存储库替换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>();
    }
}
公共类FakeRepository:IResourceRepository其中T:class
{
私有只读列表项=新列表();
专用只读IObjectFactory解析器;
公共伪造地址(IObjectFactory解析器)
{
this.resolver=解析器;
}
公共IQueryable GetAll()
{
返回此.items.AsQueryable();
}
公共作废保存(T项)
{
如果(!this.items.Contains(item))
{
此.items.Add(item);
}
}
公共作废删除(T项)
{
此。项。删除(项);
}
公共文件不能创建()
{
返回此.resolver.GetInstance();
}
}

我可以很容易地用真正的存储库(可能是Linq2Sql、ADO.NET实体、亚音速等)替换掉它。

我也可以用~LINQ to SQL来完成这项工作。我不喜欢将我的代码库的其余部分紧密绑定到LINQ生成的类,所以它们在我创建的POCO之间进行转换。谢谢。这也回答了我的问题,但我不确定如何选择两者作为答案。