Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / entity-framework

Adventures while building a Silverlight Enterprise application part #9

0.00/5 (No votes)
18 Aug 2009CPOL2 min read 8K   16  
Well, here we are again, already for part #9 of our series on using Silverlight in an Enterprise application.

Well, here we are again, already for part #9 of our series on using Silverlight in an Enterprise application. Last time we looked at some of the tricky bits on using Entity Framework in our application.

This time we want to look at a particular databinding technique, that we tend to use a lot on forms in our application. We want to look at lookup data and using classes in lookup data. What I mean is using a combobox to select some object from a list that describes part of our own data.

Below is an image of what I'm trying to do here:

As you can see we have a datagrid with computers. Whenever I select a record from the grid, this record is displayed in the form. But the casing combobox will not show me what item is selected, although I did databind to the SelectedItem property and they are the same type. The problem is that they are not the same instance.

Now if I would replace the Casing type with string and fill the combobox with a list of strings, all would work fine. This actually gives away a simple but important fact about how matching is done to select the item in the combobox. It uses some sort of comparison. So let's implement the most obvious form of comparison to make sure that equal casings actually say that they are equal, by overriding the Equals method.

public class Casing
{
public string Name { get; set; }

public override bool Equals(object obj)
{
Casing casing = obj as Casing;
if (casing != null)
{
return casing.Name.Equals(Name, StringComparison.OrdinalIgnoreCase);
}
return false;
}

public override int GetHashCode()
{
return Name.GetHashCode();
}
}

As you can see I've also overridden GetHashCode. As Visual Studio will indicate, it's best practice to always override both of the methods at the same time, so sorting follows the same logic as the Equals method. As we use the Name property to evaluate if two casings are the same, it's only logical to also use the Name properties hashcode.

Now if you look at the application, it looks like this:

Mission successful. Conclusion: if you want to be able to use lookups, always override the Equals method on your business objects.

I hope this article was helpful for you and I look forward to reading your comments and answering any questions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)