views:

104

answers:

1

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?

+2  A: 

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.

djacobson
You may think my choice of boolean property spurious... But it's the environmentally-conscious choice. ;)
djacobson
I am still using the objects I got from the datacontext, so this solution seems to work pretty well. What about adding and deleting though?
CaptnCraig
Definitely take a look at MSDN's article on CRUD with Linq-to-SQL: http://msdn.microsoft.com/en-us/library/bb386931.aspxBasically, it's all about manipulating those LtS objects. You can either use methods like `InsertOnSubmit(Employee e)` or `DeleteOnSubmit(Employee e)` directly against the LtS table (ie. `dataContext.Employees.InsertOnSubmit(new Employee() {...})`), or you can add/remove Employees from an Employee collection you've retrieved via LINQ.
djacobson