views:

311

answers:

2

I notice a lot of the examples for ASP.NET use Linq2Sql as the datasource.

Are there any examples out there which show how do use model binding with a non-Linq2Sql datasource, ie a dataset, or (as in my case) a generic list/collection of items based on a custom business object? ie

public class WebsiteList : List { public WebsiteList() { }
}

ASP.NET MVC is great, especially for it's "use whatever you want" approach. It's just a shame that so many examples are using Linq2Sql.

A: 

Linq to SQL takes your database tables and maps them to business classes. To do the same thing without Linq to SQL, just model your data classes manually, and include code to read from and save to the database.

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);
        }
    }
}
Robert Harvey
I do this ~with~ LINQ-to-SQL as well. I don't like the tight binding of the rest of my codebase to LINQ generated classes, so they are translated between POCOs I've created.
Simucal
Thanks. This also answers my question but I am not sure how to select both as answers.
Dkong
+1  A: 

A lot of the examples you can use by replacing the Linq2Sql part with your own custom repository. Since it's IQueryable you can replace it with "WebsiteList.AsQueryable()" and use most of the examples as is. For instance, here's a dummy repository I use:

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

I can swap this out easily with the real repository (which may be Linq2Sql, ADO.NET Entities, SubSonic, ...).

Talljoe