views:

31

answers:

1

Hi I have tables

Movie - ID, Name, Description, DirectorID-Fk, MusicID-Fk
Director - ID, Name 
Music - ID, MusicName 

Now I am trying to insert a new record to movie but I dont know whether Director is already existing in the DB and same with the Music).

From UI i am taking all movie information, DirectorName and MusicName.

Now when i am saving information i have to check whether with directorname and musicname first and then how to do SaveChanges() to context.

Let me know how this work.

+1  A: 

If you only have DirectorName and MusicName, you have to query the DB in order to get the existing entries (or to find out that they don't yet exist in the DB). If they do exist, add them to your movies entity; if not, create new ones and add those:

var directorToAdd = context.Directors.FirstOfDefault(d => d.Name == DirectorName) ??
                    new Director { Name = DirectorName };

var musicToAdd = context.MusicSet.FirstOrDefault(m => m.Name == MusicName) ??
                 new Music { Name = MusicName };

movie.Director = directorToAdd;
movie.Music = musicToAdd;

context.AddToMovies(movie);
context.SaveChanges();
Yakimych