Entity Framework - Insert/Update new entity with child-entities

Posted by Christina Mayers on Stack Overflow See other posts from Stack Overflow or by Christina Mayers
Published on 2010-06-08T19:59:56Z Indexed on 2010/06/08 20:02 UTC
Read the original article Hit count: 309

Filed under:
|

I have found many questions here on SO and articles all over the internet but none really tackled my problem.

My model looks like this (I striped all non essential Properties):

Everyday or so "Play" gets updated (via a XML-file containing the information).

internal Play ParsePlayInfo(XDocument doc)
{
    Play play = (from p in doc.Descendants("Play")
    select new Play
    {
        Theatre = new Theatre()
        {
            //Properties
        },
        //Properties
        LastUpdate = DateTime.Now
    }).SingleOrDefault();

    var actors = (from a in doc.XPathSelectElement(".//Play//Actors").Nodes()
    select new Lecturer()
    {
        //Properties
    });

    var parts = (from p in doc.XPathSelectElement(".//Play//Parts").Nodes()
    select new Part()
    {
        //Properties
    }).ToList();

    foreach (var item in parts)
    {
        play.Parts.Add(item);
    }

    var reviews = (from r in doc.XPathSelectElement(".//Play//Reviews").Nodes()
    select new Review
    {
        //Properties
    }).ToList();

    for (int i = 0; i < reviews.Count(); i++)
    {
        PlayReviews pR = new PlayReviews()
        {
            Review = reviews[i],
            Play = play,
            //Properties
        };
        play.PlayReviews.Add(pR);
    }
    return play;
}

If I add this "play" via Add() every Childobject of Play will be inserted - regardless if some exist already. Since I need to update existing entries I have to do something about that.

As far as I can tell I have the following options:

  1. add/update the child entities in my PlayRepositories Add-Method
  2. restructure and rewrite ParsePlayInfo() so that get all the child entities first, add or update them and then create a new Play. The only problem I have here is that I wanted ParsePlayInfo() to be persistence ignorant, I could work around this by
  3. creating multiple parse methods (eg ParseActors() ) and assign them to play in my controller (I'm using ASP.net MVC) after everything was parsed and added

Currently I am implementing option 1 - but it feels wrong.

I'd appreciate it if someone could guide me in the right direction on this one.

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework