I have a 1..* relationship between Review and Recommendations.
The relevant portion of my model (which is also the POCO mapped by EF4):
public class Review
{
public ICollection<Recommendations> Recommendations { get; set; }
}
On an Edit View, i represent the Recommendations as a set of checkboxes.
When i try and add a new Recommendation as part of editing the Review (e.g check another box), nothing is happening - and i know why...
I use the "stub technique" to update my entities - e.g i create a entity with the same key, attach it to the graph, then do ApplyCurrentValues
. But this only works for scalar properties, not for navigational properties.
I found this StackOverflow question which looks good, but i am trying to work out how to get this to work with POCO's/Repository (and ASP.NET MVC - detached context).
As i'm using POCO's, review.Recommendations
is an ICollection<Recommendation>
, so i can't do review.Recommendations.Attach
. I'm not using Self-Tracking Entities either, so i need to manually work with the graph/change tracking - which hasn't been a problem until now.
So you can visualize the scenario:
Review:
- Recommendations (
ICollection<Recommendation>
):
- RecommendationOne (
Recommendation
)
- RecommendationTwo (
Recommendation
)
If im on the edit view, two of the checkboxes are already checked. The third one (representing RecommendationThree) is unchecked.
But if i check that box, the above model becomes:
Review:
- Recommendations (
ICollection<Recommendation>
):
- RecommendationOne (
Recommendation
)
- RecommendationTwo (
Recommendation
)
- RecommendationThree (
Recommendation
)
And so i need to attach RecommendationThree to the graph as a new entity.
Do i need hidden fields to compare the posted data the existing entity? Or should i store the entity in TempData and compare that to the posted entity?
EDIT
To avoid confusion, here is the full app stack call:
ReviewController
[HttpPost]
public ActionResult Edit(Review review)
{
_service.Update(review); // UserContentService
_unitOfWork.Commit();
}
UserContentService
public void Update<TPost>(TPost post) where TPost : Post, new()
{
_repository.Update(post); // GenericRepository<Post>
}
GenericRepository - used as GenericRepository<Post>
public void Update<T2>(T2 entity) where T2 : class, new()
{
// create stub entity based on entity key, attach to graph.
// override scalar values
CurrentContext.ApplyCurrentValues(CurrentEntitySet, entity);
}
So, the Update
(or Add
or Delete
) Repository methods needs to be called for each recommendation, depending it's new/modified/deleted.
See Question&Answers more detail:
os