EF ComboBox not displaying SelectedItem Binding

你说的曾经没有我的故事 提交于 2019-12-03 21:10:08

问题


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?


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/18808331/ef-combobox-not-displaying-selecteditem-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!