简体   繁体   中英

Entity Framework Detached Entities Not Equal

I'm working with Entity Framework 6 and I'm trying to use Entities without change tracking. So I apply

MergeOption = MergeOption.NoTracking

to the ObjectQuery before fetching my Entities.

In my application I have a Status dropdown and the Statuses are entities. The Status dropdown's ItemSource would be set to the EntityCollection returned by the object query.

I have an Order entity which contains a Status. If I dont change the MergeOption and use the default, I can set the SelectedValue to bind to the Order's Status and it works properly. However if I do use NoTracking, the appropriate status is not selected in the dropdown.

Is there a way to use detached entities as an ItemSource and still have SelectedValue bind properly?

As the comment stated, you are comparing by reference; status and myOrder.Status are two different objects. If you load the same entity from the context two different times (but from the same context instance), you will get the same object, which is why they are equivalent.

You could compare by primary key or by the values of each property of the entities depending on what you want equivalence to mean for this entity.

if( status.Id == myOrder.Status.Id )

if( status.FieldA == myOrder.Status.FieldA &&
    status.FieldB == myOrder.Status.FieldB )

In this blog post , which I posted in my comment above, the author describes how to do this by including foreign key columns in the model. Some people may not want the foreign key column included in their models so this wouldn't suit them (including myself), but I wanted to post an answer because this would solve my problem as described above.

In the XAML you would just use something along these lines so that the ComboBox is using the Status_Id property of the Order model to compare against the Id property of the Statuses within the StatusCollection:

<ComboBox ItemsSource="{Binding StatusCollection}" 
  DisplayMemberPath="Name" 
  SelectedValuePath="Id" 
  SelectedValue="{Binding MyOrder.Status_Id,Mode=TwoWay}" 
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM