Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm making a few assumptions for my answer: 1. We're only inserting new movies, and not updating movies already in the DB. 2. We're using the Entity Framework to do the insert. 3. People in the movies being added aren't already in the DB associated with other movies. 4. Every movie has a cast, and every cast member has at least one character.</p> <p>At the risk of getting thrown off the cool kids bus my solution doesn't use LINQ, although I'm sure it could be modified to do so. Note that with EF you don't need to set both ends of the association to insert it into the database.</p> <pre><code>// Lookup is necessary because a person might be in more than one movie. var personLookup = new Dictionary&lt;string,Person&gt;(); foreach (var contractMovie in dataContractMovies) { var movie = new Movie() { Title = contractMovie.Title }; foreach (var contractPerson in contractMovie.Cast) { if (!personLookup.ContainsKey(contractPerson.Name)) { personLookup.Add(contractPerson.Name, new Person() { Name = contractPerson.Name }); } var person = personLookup[contractPerson.Name]; foreach (var contractCharacter in contractPerson.Characters) { var character = new Character() { Name = contractCharacter.Name, Person = person, Movie = movie }; dataContext.Characters.Add(character); } } } dataContext.SaveChanges(); </code></pre> <p>If the DataContract mapped Movie to Character instead of Person (like you suggested in your comments) you could get away with something more like this:</p> <pre><code>var personLookup = new Dictionary&lt;string, Person&gt;(); var movie = dataContractMovies.Select(m =&gt; new Movie { Title = m.Title, Characters = m.Characters.Select(c =&gt; new Character() { Name = c.Name, Person = LookupPerson(c.Person, personLookup) }).ToList() }); public Person LookupPerson(string personName, Dictionary&lt;string, Person&gt; personLookup) { if (!personLookup.ContainsKey(personName)) { personLookup.Add(personName, new Person() { Name = personName }); } return personLookup[personName]; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload