WPF, EF4, and relations

Tyrsius Source

Relations is probably the wrong word to use, but Data tables are what I have used before. I have EF4 pulling from a SQL database. Tables like Customer, Company, Department; things that usually go into Comboboxes for selection. I am holding them in static lists (only needs to populate on app startup), and I have a few comboboxes itemssource bound to them, which makes setting "relating" a specific selection easy by binding the selected item from the ViewModel.

My problem is, in a few places I just need a the name associated with an ID in a datagrid for display only. A couple hundred rows with a CompanyId that needs to be a CompanyName. I am concerned about performance here. I could use the DB FK's to get the names during the lookup, but thats seems like a waste since I have them all in static lists. I also don't know if Lazy loading would mean they get looked up during data binding, or during the initial query.

What is the best solution here? Can you make a wpf value converter using static lists? Should I perform a foreach on the data after getting it, and looking the values in the static list, storing the Name in the object?

wpfentity-framework-4ivalueconverterdatarelation

Answers

answered 7 years ago Jeff #1

You could build this logic into your query:

var viewModels = (from c in objectContext.Customers
                 select new MyGridViewModel {
                       CustomerId = c.CustomerId,
                       CompanyId = c.CompanyId,
                       CompanyName = c.Company.Name
                 }).ToList();

This will eliminate the need to fetch all of your columns (only CustomerId, CompanyId, and Company Name will be returned. You also won't be lazy loading the Customer's Company.

Then you can simple bind your View Models to the grid:

myGrid.ItemsSource = viewModels;

answered 7 years ago devuxer #2

Couldn't you just inject the static data required for ComboBoxes into the constructor of each of your ViewModels?

For example, in your constructor, you might pass in a List<Customer> customers or if you want to avoid using entity objects, you could pass in a List<CustomerViewModel> customerViewModels, which has only the columns you need for populating combo boxes.

If you are using a dependency injection framework, this would be particularly easy, but even if you're not, it shouldn't be too bad, and it's good practice.

comments powered by Disqus