I have a Silverlight 4 application for a simple 'TODO' list. The problem I'm having is that databinding is hooking up relationships on my TODO
object, which causes the RIA data context to add it to the DataContext.TODOs
list before I want it there.
I want to treat the object as new and detached until I'm explicitly ready to add it to the datacontext.
Here's how it works :
I've got my TODO
entity which is associated with a Status
(RIA services entity relationship).
I create a new TODO()
entity which is passed to a ChildWindow
popup. Notice that I don't add this new entity to my datacontext.
new CreateTODOPopup(new TODO()).Show();
In the DataForm in my ChildWindow I have a combobox for Status
which is databound to DataContext.Statuses
.
The problem is that the action of selecting a Status
from the dropdown actually associates the entity to the context for me - ending up giving it a state of EntityState.New
and actually adding it to the DataContext.TODOs
colleciton.
This would be fine except that it now appears in the main TODO list in the main frame. I don't want this becasue it hasn't been committed by the ChildWindow yet.
How can I solve this? Either by preventing the entity from becoming attached - or by somehow hiding it from any controls it is bound to until it has been added.
Have you tried using Context.Detach on the object so that you clearly specify that it shouldn't be in the context? Then you can Context.Attach it again before you save it.
I guess one way would be to use a PagedCollectionView and filter out 'New' entities - but there has to be something obvious you're missing.
You should be able to get the behavior you want by adding another 'MyProject' property to the TODO entity using a partial class. In your popup you could set the 'MyProject' property instead of the 'Project' property. When you save your TODO, you could then apply the 'MyProject' value directly to 'Project'. A little circuitous, but it should give you the behavior you'd like.
Kyle
IMPORTANT: After 3 days of struggling with a horrible race type condition it turned out to be directly related to this problem. Basically the conclusion is - if you're trying to create entities and not add them to the data context then don't if you don't want race conditions and unexpected behavior. I'm pretty sure this is a RIA services bug.
What I was doing :
new TODO()
and passing it to my viewTODO
with all the foreign key tables, such asStatus
andAssignedTo
TODO()
to the list if it wasn't already present in theDataContext.TODOs
entity set.What the framework did by itself:
TODO
to theDataContext.TODOS
collection. This is just the way entities work.Why this is bad:
New
- sometimes up to 20 of them and then getting resaved as new duplicate rows.How i fixed it :
Here's some sample code for adding entities immediately on creation - no race condition:
This code did NOT work, and causes race conditions - adding entities after foreign key constraints have already been set: