Proper way to use Linq with WPF

Posted by Ingó Vals on Stack Overflow See other posts from Stack Overflow or by Ingó Vals
Published on 2010-06-15T13:07:22Z Indexed on 2010/06/15 14:02 UTC
Read the original article Hit count: 305

Filed under:
|
|

I'm looking for a good guide into the right method of using Linq to Sql together with WPF.

Most guides only go into the bare basics like how to show data from a database but noone I found goes into how to save back to the database. Can you answer or point out to me a guide that can answer these questions.

I have a separate Data project because the same data will also be used in a web page so I have the repository method. That means I have a seperate class that uses the DataContext and there are methods like GetAllCompanies() and GetCompanyById ( int id ).

1) Where there are collections is it best to return as a IQueryable or should I return a list?

Inside the WPF project I have seen reccomendations to wrap the collection in a ObservabgleCollection.

2) Why should I use ObservableCollection and should I use it even with Linq / IQueryable

Some properties of the linq entities should be editable in the app so I set them to two-way mode. That would change the object in the observableCollection.

3) Is the object in the ObservableCollection still a instance of the original linq entity and so is the change reflected in the database ( when submitchanges is called )

I should have somekind of save method in the repository. But when should I call it? What happens if someone edits a field but decides not to save it, goes to another object and edits it and then press save. Doesn't the original change also save? When does it not remember the changes to a linq entity object anymore. Should I instance the Datacontext class in each method so it loses scope when done.

4) When and how to call the SubmitChanges method

5) Should I have the DataContext as a member variable of the repository class or a method variable

To add a new row I should create a new object in a event ( "new" button push ) and then add it to the database using a repo method.

6) When I add the object to the database there will be no new object in the ObservableCollection. Do I refresh somehow.

7) I wan't to reuse the edit window when creating new but not sure how to dynamically changing from referencing selected item from a listview to this new object. Any examples you can point out.

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf