4

I am using Entity Framework and Caliburn.Micro to implement an MVVM application.

Basically, I have set up AuthorModel and BookModel in a one to many relationship - an Author having multiple Books and a Book having only a single Author.

I have a SelectBookWindow where I use DbContext to load ObservableCollection<Book>, from where I select a Book I want to view/edit. I then pass the selected Book as a parameter to an EditBookWindow where I have a combobox enumerating all the Authors but with the current Author selected.

In here, I load up ObservableCollection<Author> using a different instance of DbContext and set it as the combobox's ItemsSource and as well as do SelectedItem="{Binding Author}". (Author being a virtual property of Book)

The ComboBox displays the Author list correctly. However, it doesn't seem to display the Book's Author as its SelectedItem.

Is this because I am using a different instance of DbContext? If so, how can I rectify this problem?

howellmartinez
  • 1,195
  • 1
  • 13
  • 24
  • 1
    You can pass the context to the second window along with the selected book, though i'm not certain it's the best idea... – UIlrvnd Sep 15 '13 at 05:59

2 Answers2

3

Yes it is. Because the author in ItemsSource is referencing to a different object although the content is the same as the one that is bind to SelectedItem.

I don't know much about EF, I guess you can use the same context for the two entities. Or override the equals (and gethashcode) of the Author class to compare the content then return true if the same.

Eben
  • 554
  • 3
  • 11
1

As Eben mentions, the Author referenced by the ItemsSource will be a different object (although it happens to reference the same entity).

I think your approach of using a new DbContext for both of your windows is correct, you can run into problems if you have persisting/shared DbContexts; it makes sense to load an EditWindow with a new context, perform your edits, and dispose of the context.

One option is to Detach your Book entity from the old DbContext, and Attach it to your new context: (a good explanation here Entity Framework 4 - AddObject vs Attach).

I would probably just favour using the passed Book entity to reload the selected Book from the new context e.g. using DbSet<TEntity>.Find, and using that retrieved entity to bind to the SelectedItem (rather than the one you're passing across windows).

Community
  • 1
  • 1
Chris
  • 8,268
  • 3
  • 33
  • 46