>Hi everybody,
>
>I am wondering if you can point me to the best practice approach in EF when we're talking about related tables.
>
>Say, I see the following code for a similar situation which I am currently working with:
>
>
> public void AddTemplate(Template template, IEnumerable<Sites> assignedSites)
> {
> _templateRepository.Add(template);
> UpdateTemplateRemoteSites(template, assignedSites);
> }
> public void UpdateTemplate(Template template, IEnumerable<Sites> assignedSites)
> {
> _templateRepository.Update(template);
>
> UpdateTemplateRemoteSites(template, assignedSites);
> }
>
>where the last method is:
>
>
> private void UpdateTemplateRemoteSites(Template template, IEnumerable<Sites> assignedSites)
> {
> IEnumerable<Sitelink> currentSiteLinks = _siteLinkRepository.GetSiteLinksForTemplate(template.TemplateId);
> IList<short> currentSites = currentSiteLinks.Select(x => x.SiteNo).ToList();
> IList<short> sites = assignedSites.Select(x => x.SiteNo).ToList();
> AssignRemoteSitesToTemplate(template, currentSites, sites);
> RemoveRemoteSitesFromTemplate(template, currentSites, sites);
> }
>
>So, the template is associated with another table storing the sites. In the interface we're using the Mover for Assigned and Available Sites.
>
>I am working on a similar scenario and I can just mimic that code but I am not 100% sure it's the best practice approach. As you can see, we save the information in the main table first (in the Adapter code) and then do the related table save. Based on that code I suspect that it happens in different SQL Server session.
>
>So, my question is - is the listed approach OK or there is something that needs to be added to make it better?
>
>Thanks in advance.
If the entities are modified within the context then the changes should be saved automatically. Presumably this is in a web scenario where the context is not available ?
In that situation there are a few approaches :
EF's Self-Tracking entities :
https://msdn.microsoft.com/en-us/library/vstudio/ff407090(v=vs.100).aspxTrackable Entities :
https://trackable.codeplex.com/Googling ' EF Updating Child Entities' will give a few alternatives - mostly based on retrieving the object graph from the context, walking the updated object graph and updating the retrieved entity accordingly then saving it.
Interesting Linq based approach to the latter :
http://stevemichelotti.com/handle-insert-update-delete-of-child-entity-in-tiered-application/