user3530012
user3530012

Reputation: 740

MVVM: Loading large data records

As I've learned from MVVM pattern there is an ObservableCollection in every ViewModel which holds all the models. I have a ViewModel implemented like this:

    public class ViewModel {

        public void LoadData() {
            Items = new ObservableCollection(_logic.Select());
            IsDataLoaded = true;
        }
    }

Let's say _logic.Select() returns a List<> of all the records in the table. Now what if the data is large? What if I have thousands or maybe hundred thousands of records in the table? Should I load them all in the ObservableCollection? It takes a lot of time for them to be loaded.

Upvotes: 2

Views: 1602

Answers (1)

Nahuel Ianni
Nahuel Ianni

Reputation: 3185

You shouldn't load all the data from the Database, load only what you need. Think about how badly it would hurt your performance to load 1000 registries if you only need one:

You need to query the DB. Use the server to create and execute the query and keep all data somewhere, usually in memory. Then send it to the client. The client will also need to keep the data somewhere.

As said before, you can use server side paging AND/OR filtering.

The logic is simple, on your server you probably have a "return MyEntity;" or some method like that.

Instead of doing it, why not implement the "Take" extension method provided by Linq.

Edit:

Found this example: http://blogs.msdn.com/b/brada/archive/2009/07/17/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-8-wcf-based-data-source.aspx

That post covers more than paging, but pay special attention to:

public IEnumerable<SuperEmployee> GetSuperEmployees(int page)
{
    using (var context = new NORTHWNDEntities()) 
    {    
        var q = context.SuperEmployeeSet.OrderBy(emp=>emp.EmployeeID).Skip(page * PageSize).Take(PageSize);    
        return q.ToList(); 
   }
}

Check that qhe value of "q" uses the Skip and Take method to go to a specific item and from there, take an X amount of them.

Finally, sorting is really similar to the code above, but more complex. You can use the Where method from Linq to implement it.

Upvotes: 3

Related Questions