CRUD in Winforms with linq-to-sql - winforms

I have a simple winforms application that I am connecting to my database with linq-to-sql.
I have generated the classes directly from the database, and I have a DataAccess class that wraps my datacontext and can give me whatever I need.
I have a view that uses an object datasource to populate a DataGridView and a set of related text fields, etc.. for my entity (lets call it EmployeeView)
The view loads all of the existing rows, and as I click through the grid, the fields update appropriately.
If I change fields, the changes will persist through record changes, but I am not sure how to save changes through my data access layer. How can I detect which records are dirty and need to be saved? How do I then save them? What is the best way to add new records? Delete records?
I can find a lot of resources online, but none with the kind of examples I need. Can anyone help me out with some of the basic patterns, or point me to a good place?

The most basic way to use LINQ-to-SQL classes, I believe, is to instantiate a list of them (let's use Employee, for example) to contain the Employees you wish to (potentially) edit. When the properties of those Employee objects are changed, the objects are automatically "dirtied", and a call to DataContext.SubmitChanges() will persist them.
List<Employee> employees = (from e in dataContext.Employees where e.Salary > 50000 select e).toList();
foreach(var employee in employees)
{
employee.CanAffordToyotaPrius = true;
}
dataContext.SubmitChanges();
If you're wrapping the DataContext and only altering the properties of the wrapper object with the DataGridView, you'll need some way to bubble those changes down into the underlying LINQ-to-SQL objects you used when you selected the data. For example, you could use the setter on your wrapper's properties to also set the underlying LtS object's properties.

Related

Entity set assigned to datagridview will disable sorting

I use Entity Framework. When I bind an entity set to a standard DataGridView control I lose sort-by-click-on-header functionality. I even tried to bind the entity set to a binding source first but results are the same.
Also if I try to sort a column from code I even get an exception that an interface is not implemented... Are standard EF classes un-sortable (would be a bummer)? Needless to say, sorting works if a DataView is provided as data source.
How could I get around this problem? Thanks.
Late to the party but thought I'd at least post an answer... There are two ways to achieve this with little fuss (actually the same method, just slightly different route).
So we have a basic EF context query, pre-execution.
var query = context.Projects
.Where(x => x.Division == selectedDivision);
Load the query so entities are in the local cache. Then point the DGV's binding source to the Local cache's synced BindingList
query.Load();
projectBindingSource.DataSource = context.Projects.Local.ToBindingList();
OR... There were times when I didn't want/need change tracking or the cache "got in the way" of other operations so I needed a non-tracked collection.
Execute the query without tracking and load it's result into an ObservableCollection (Which is what .Local is). Point the DGV's binding source to the ObservableCollection's synced BindingList
var locs = new ObservableCollection<Location>(query.AsNoTracking().ToList());
locationBindingSource.DataSource = locs.ToBindingList();
All text, numeric, and bool columns will have sort enable for header-click. What won't sort are columns for Navigation Properties: Say a Project has an Owner navigation property, since I have Owner entity's ToString() override display the Owner.FullName property I will see an Owner column with the FullName value but I assume the sorter still sees the column's type as the System.Data.Entity object (instead of the bubble up text that is displayed) so doesn't have a default sorter for it.

How to assign context and refresh it in Entity Framework?

I created a new entity object and bound it to controls in another window (edit window). After modifying and saving I assigned a new entity object into the one in the main window. The old entity object is bound into a datagrid, now I want the datagrid to display the data that I had modified and saved.
ObjectContext.Refresh Method (RefreshMode, Object) seems to be what I want but I don't know how to use it correctly.
In short :
I have a main window with datagrid displaying the whole data of the table. Users can pick one row and edit it in a edit window. After saving, the datagrid should display what has been modified.
Your best bet here is to use an ObservableCollection as your data source for the datagrid instead of the query.
And look at implementing INotifyPropertyChanged interface in your Customer class.
The ObservableCollection is initially populated by the database query. User changes are made to elements within the ObservableCollection and once complete you then just need to trigger transferring the changes to wherever you originally obtained your list of Customer objects
By doing this changes made both to the collection of Customers and to individual Customer objects (if present within the datagrid) will be automatically updated for you.
edit
I must admit that I'm a bit rushed to offer up any code at the moment, but here's a pretty good article that explains how to use ObservableCollections and classes that implement INotifyPropertyChanged. It also has code examples, which although in VB.NET should give you enough of an idea to get started.
In effect you separate your code into distinct layers UI (View), business logic (View Model) and data layer (Model where your entity framework resides).
You bnd your datagrid to the ObservableCollection type property in your Customers class and your edit csutomer window is bound to as instance of your Customer class.

ViewModel -> Model interaction

Suppose I have a WPF/MVVM application for managing some hypothetical customers :).
Domain model contains an entity named Customer (represented as a POCO in code).
The main screen contains a grid, bound to a view model (CustomersViewModel) that loads its data from Repository< Customer>.
The main screen also allows to create new customers (and save it to the DB).
Suppose I need to implement 'add customer' use-case. The most obvious approach is as follows:
Present the user with a dialog window to be filled out with new customer data.
Handle 'Save' button click in the ViewModel.
Create customer (var new_customer = new Customer(..)) domain object using the data from the dialog (step 1).
Call Repository< Customer>.Save(new_customer) to save the new customer to the DB.
Reload CustomersViewModel with fresh data from the DB so that newly added customer is visible in the grid.
Personally I don't like this 'quick-and-dirty' way (because of need to reload the full list of customers from DB every time a new customer is added).
Can anyone suggest a better approach (that wouldn't require refreshing the customer list from the DB)??? I feel there gotta be some best practice for handling scenarios like that:) ).
Thanks in advance!
If the saving of the Customer is successful, why can't you just add that single Customer instance to your collection of customers? No need to re-load all customers unless the user explicitly refreshes the view (usually via a refresh button).
If you are loading the list in your view through a binding (to a list of customers) you can just add the new customer to that list and everything is alredy ;-)
I have a similar application where in the object is created in UI. I solve it by adding the object in VM and then syncing it with Model on click of Save button.
I am assuming you have a list of CustomerViewModel in CustomersViewModel to which the grid view is bound to. You can add a new CustomerViewModel object to the list in CustomersViewModel. While saving the ViewModel data back into the model, the model gets in sync with VM. No need to refresh VM back from Model unless somebody else apart from your app is changing the Model data.
You could create an ObservableCollection<Customer> and fill it with the customers from the database which you want to show in the View. When you add a new customer then add it to this collection as well as save it into the database. The CustomersView binds on the ObservableCollection and is updated automatically without the need to refresh the data from the database.
The BookLibrary sample application of the WPF Application Framework (WAF) shows how this can be done.

WPF LINQ DataContext Refresh not reading new records in the sql database table

I have a LINQ datacontext and a ObservableCollection holding records for a Companys table in SQL
Changes to the current records and new records made to the current datacontext (DataDC) are reflected when I do a
DataDC.SubmitChanges();
However if I have another Window with a separate DataContext to the same tables, if I modify fields for records that currently exist in both DataContexts (ie Company Name modified) these changes are seen when I do a
DataDC.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, Companys);
However if the OTHER window/datacontext created a new record or if I use SQL explorer to create a new record, these new records do not show in the DataContext.Company table even after a
DataDC.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, Companys);
I've tried different Modes.
So why doesn't a .Refresh(....) Load new records, but will reflect changes made to records that exist?
Am I missing something?
I can't see a way to just refresh the DC with completely all new data from the SQL tables?
The Refresh() method doesn't retrieve new records from the database.
I'm not entirely sure why that is - just one of those choices that the Linq to SQL product team made (presumably with good reasons). It could have something to do with the fact that the refresh method
is primarily designed for optimistic
concurrency conflict resolution 1
To get the newly entered records you will need to either:
Reissue a new query on the same DataContext
Create a new instance of your DataContext
Which option you go with depends on context (no pun intended). Things to bear in mind are the intended Unit of Work nature of the Linq to SQL DataContext and the intended short life span of the Datacontext.
Dinesh's Cyberstation - a Microsoft blog from a member of the Application Frameworks team.
If you're having both windows in the same app, I don't see any reason not to use just one DataContext and pass a reference of your original datacontext to your second window.
Appologies, Ive found out more.
The under lying Data Context DOES reflect the chnages live in the data base.
Its my fualt, I ASSUMED that
DataDC.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, Companys);
Refreashed the 'collection' (Companys) , I mean thats what intellisense actually says. But it doesnt.
But if you clear the collection and then reload them as below, this works. The problem was not with the data collection, just that DataDC.Refresh doesnt do what I thought it did.
public void LoadCompanys(ProActiveDataClassesDataContext dataDC)
// This loades the under lying datatables into the Observable collection
{
this.Clear();
foreach (Company thisCompany in dataDC.Companies)
{
this.Add(thisCompany);
}
}

MVVM WPF ViewModels for Adding New Entity

My concept for MVVM in WPF is that we have a ViewModel for every Model in your application. This means that if we have Customer class (entity) then we will have CustomerViewModel. The CustomerViewModel will have all the properties which are necessary to represent a customer. The CustomerView usercontrol will be responsible for creating the UI for the Customer model.
Now, let's say that we are adding a new customer. So, we have a form which consists of FirstName, LastName etc. Do we need a ViewModel for this scenario. I mean all I have to do is to take all the input values from TextBox and create a Customer object and then save it to the database. Why should I bother creating a ViewModel for this scenario?
First of all, that is not the main purpose of MVVM, to "mirror" everything. The View should provide the means for a user input, and certainly not process calls to any of the database layers. The ViewModel should be a GUI-agnostic application backbone, and it definetly should handle the creating of customers.
That said, what you should do, is have a ViewModel which represents a workspace for handling customers, and not just a customer ViewModel. If you really want to save on a few objects being created, add to that workspace the possibility to create and add a new customer (not CustomerViewModel). That way, you can have a View of the workspace which has elements for each relevant/required property of the customer, and by invoking some command added to that workspace ViewModel, you could get the current values filled in those (data bound to ViewModel) View elements directly to the customer model.
Consider if you could probably drop the specific customer (and other Model) ViewModels if you refactor things a bit, it would be good practice to keep things from adhering blindly to a certain pattern without explicit cause.
Let's pretend for a second that there is no business model. The only thing you have is a view. If you were to model just that view, without any knowledge of what the data means elsewhere in the system, that is a ViewModel.
The goal of a ViewModel is to, well, model the view it backs. This is a different goal than modeling the idea of a customer in your business domain. To say you will have have one ViewModel per business entity, then, is to say you will have one view per business entity, which leads to run-of-the-mill data-focused UI.
In your particular case, think about the customer edit view. It has fields that correspond to a customer's properties, and thus seems like a natural fit for binding to a customer directly. However, where on the customer object is the "Submit" action modeled? Where is the "Cancel" action modeled? Where is it modeled that field X is an enumerated value selected from a list?
How about the password? If persisted as a binary hashed value, does the view know how to hash its text? What if the system has password strength requirements?
The ViewModel is the mortar between the business model and the UI. It takes concerns from one and translates them into terms of the other. It is the point at which all the above issues are addressed. To say a ViewModel isn't necessary is to ignore its necessity.
You don't need to have a separate ViewModel for Add, you only need a single ViewModel which should do Edit and Add scenarios. If you can delete the record from the edit page than that ViewModel should also have the ability to delete. Your ViewModel should reflect the functionality your View exposes regardless of data.
I think you should reconsider having a single ViewModel for each model. I like to think of ViewModels as normalizing behavior inserted of data. By having a ViewModel for each Model class you will run into architecture issues sooner or later. I look at the application from top down overview, what is my UI trying to accomplish and from there I will get to the ViewModel and eventually I will get to my DataFactory and how the ViewModel maps down to data is almost always not 1 to 1 except for the most simplistic Views. If you try to map 1 to 1 you will have bad UI or your data will not be normalized very well.
The Stack we have here is:
View
ViewModel (Controls everything the user can do in the view, wraps properties from our POCO's)
DataFactory (Maps our POCO's to Entity Framework objects and CRUD)
POCO's (Business Logic, all rules and validation)
Entity Framework (Model, Data Access)
One note here is that ViewModel contains properties from multiple POCO's!
We inject the DataFactory through StructureMap and Unit test with xUnit along with Moq.
To answer you second question I would create a separate view only view to drop in as a user control. But you should still have a CRUD ViewModel in you app that encapsulate all that functionality in a user friendly way.
Thanks.
One reason for this VM abstraction is for testability. Another reason why you want a ViewModel is because it's basically a Data Transfer Object that might be a combination of fields from multiple models in a single container that is more relevant to your current view. Yet another reason to have VM is to take advantage of WPF two ways binding capabilities.
Using your regular model (plain POCO), you can update the View when your model change, but since your model does not implement dependency properties (most likely), you won't be able to take advantage of updating your model when the value in WPF control changes. Which mean you have to manual add a handler and do the copy this value from this control back to the model kind of thing.

Resources