views:

174

answers:

1

After using a global Linq to Sql DataContext and having unwanted inserts, I decided to use a detached methodology. I did this through a methods class that serves as a abstraction layer from my buisness objects to my DAL. There is one DataContext per each CRUD call so I can call something like this.

using (DatabaseMethods<TEntity> db = new DatabaseMethods<TEntity>())
{
    return db.GetAll();
}

In the DatabaseMethods constructor I create a new DataContext. In DatabaseMethods.Dispose(), I dispose the context, and set it to null.

GetAll in DatabaseMethods uses the dataContext to get the list:

return this.dataContext.GetTable<TEntity>().ToList();

The problem is when I bind to the Entity, my comboboxes are filled (they are filled by a similar getAll call), but the selectedItem is not shown. (ex: a Gun has a GunType (linked by a foreign key)), but a grid (bound to the same object) on the same page is showing the text of that item. Could it be that WPF doesn't know how to compare the two and know that they are the same? My unit tests testing my DatabaseMethods show the loading is happening correctly.

I've tried turning off the DeferredLoadingEnabled for all of my DataContexts and using the LoadWith function to get the the descriptor at load time, but it must still be null when the UI first grabs it. It seems that the UI has to try to get the property once, then it works the second time. When debugging the property is loaded (through the LoadWith setup).

This is a very specific problem, and I've been looking all over for some clue as to what my problem is. If anyone has some suggestions, I would appreciate them.

EDIT: The answer is to override Equals. Typing out the question helped me figure it out. Then I refreshed this page and saw Michael Petito answer.

+1  A: 

You are using a different data context within each instance of your DatabaseMethods class. The GunType instance loaded by your first data context, used to retrieve your Gun, will be a different instance than the equivalent GunType loaded by your second data context used to populate your comboboxes.

Since the two GunTypes are different instances, they will not be equal, and you will not get the correct selected item in your combobox, unless you explicitly override the Equals method inherited from Object by your GunType class.

Ex:

public override bool Equals(object other)
{
    return other is GunType && ID == ((GunType)other).ID;
}
Michael Petito
Thanks for the quick response. I had just come to that conclusion myself, a few minutes before refreshing this page and seeing your answer. After overriding equals, the selected items are working again!!
Kevin