EF ComboBox Does Not Display SelectedItem Binding

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

Basically, I created AuthorModel and BookModel in a one to many relationship - to an Author who has several books and books that have only one author.

I have a SelectBookWindow where I use a DbContext to load an ObservableCollection<Book> , from where I select the book that I want to view / edit. Then I pass the selected book as a parameter to EditBookWindow, where I have a combobox listing all the authors, but with the selected author.

Here I load the ObservableCollection<Author> using another DbContext instance and set it as combobox ItemsSource , as well as do SelectedItem="{Binding Author}" . ( Author is a virtual property of Book )

ComboBox displays the list of authors correctly. However, it does not appear to display the Book Author as a SelectedItem.

Is it because I'm using another instance of DbContext? If so, how can I fix this problem?

+4
source share
2 answers

Yes it is. Since the author in the ItemsSource refers to another object, although the content is the same as the one that is attached to the SelectedItem.

I know little about EF, I think you can use the same context for two objects. Or override the equals (and gethashcode) of the Author class to compare the contents, then return true if it is.

+3
source

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

I think your approach to using the new DbContext for both of your windows is correct, you may run into problems if you have persistent / shared DbContexts ; it makes sense to load EditWindow into a new context, make changes and get rid of the context.

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

I would probably just approve of using the passed Book object to reload the selected Book from the new context, for example. using DbSet<TEntity>.Find and using this restored object to bind to SelectedItem (and not to the one you go through windows).

+1
source

Source: https://habr.com/ru/post/1502221/


All Articles