views:

1289

answers:

1

Hello everybody,

I have a problem with Linq and ObservableCollections in my WPF application.

Context of the problem:

I've created a very simple SQL database with two tables: User and BankAccounts. The User Table has an one-to-many relationship with the BankAccounts Table. Next I've created Linq-to-SQL dataclasses, which worked fine ==> the assosiation between the two tables was detected as well.

Next I've created a function to retreive all Users which works fine:

DataClassesDataContext dc = new DataClassesDataContext

var query = from u in dc.Users
            select u;

Now suppose I want to add a new BankAccount to each user (not very likely but still). I could add the following code

for each(User u in query)
{
   u.BankAccounts.Add(New BankAccount());
}

The above works all fine. The BankAccounts property is automaticly part of the User class, due to the assosiation in the database and Linq DataClasses.

However, in my application I first add the query results to an ObservableCollection. Hereby I could use all sorts off databinding and changenotification. This is accomplished by the following code;

ObservableCollection<User> oUsers = new ObservableCollection<User>(query);

Problem: Within the ObservableCollection I can't do anyting with the users BankAccounts property because it is now of type EntitySet<>. So I can't do the following statement anymore.

for each(User u in oUsers)
{
   u.BankAccounts.Add(New BankAccount());
}

Somehow, when queryresults are added to an observablecollection It is not possible to acces the user.BankAccounts properties anymore. However, it is possible to bind the BankAccounts Property to any control, like a listbox, and it contains the correct data.

Does someone now how I can create an observableCollction (or similar collection) from wich I can access these "assosiated" properties? I'm realy looking forward for to a solution.

Thanks in advance! Best regards,

Bas Zweeris E: [email protected]

A: 

Keep track of the original query which will implement IQueryable, you can run any further queries you need against that.

The ObservableCollection should just be for WPF to have something to bind to - its very useful if you want to add a new collection item but not have it pushed to the database before the user has had chance to edit it.

eg.

// Create a new blank client type
var ct = new ClientType()
{
    IsArchived = false,
    Description = "<new client type>",
    Code = "CT000",
    CanLoginOnline = true
};

// Tell the data source to keep track of this object
db.ClientTypes.InsertOnSubmit(ct);

// Also add the object to the observable collection so that it can immediately be shown in the UI and editted without hitting the db
clienttypes.Add(ct);
Kieran Benton