Duplicates in databaseProblem with LINQ in C#Databinding issue with stopwatched elapsedHow do I populate current class with new class values?How to register and use different implementation of same interface?Null Foreign Key in Entity Framework code firstC# LINQ join with conditional where clause on two different data setsASP Core MVC Scaffolding SelectList (RC1) not populating dataget int value from XmlTextAttribute when deserialize xml to class in c#C# & XAML - Display JSON in ListView from Wunderground API

Do Klingons have escape pods?

Birthplace vs living place

What is the quickest way to raise Affection?

Why is it ethical for Ambassador Sondland to have been given an ambassadorship for campaign contributions?

What is the largest piece of space debris volumetrically?

Employer wants me to do something explicitly illegal

Is there any theory why (for Bitcoin) the discrete logarithm problem is so hard to solve?

Are there primes arbitrarily close to powers?

Starting with D&D: Starter Set vs Dungeon Master's Guide

Bought a book that is in the public domain ... but the T&A of company says I can't redistribute it

How can I offer my prayers for an atheist?

What are the benefits of multi-file programming?

What's a good use case for SELECT * in production code?

How does Wall of Roots interact with +1/+1 counters?

I peer reviewed a paper and found it to be sound - technically and language-wise. How should I write the review report?

Miniseries in post-rapture US with good/evil conflict

Do I even like doing research?

What world is this where 6 + 6 = 10?

Is there a product for channeling water away from water appliances?

Simulate reproduction in a population of oozes

Barring Epic Boons, is there a way to gain immunity to fire damage?

Is it good to take a fianchettoed Bishop?

What is optix & opencl in 2.81

Why is it runway "1" instead of "01" in America?



Duplicates in database


Problem with LINQ in C#Databinding issue with stopwatched elapsedHow do I populate current class with new class values?How to register and use different implementation of same interface?Null Foreign Key in Entity Framework code firstC# LINQ join with conditional where clause on two different data setsASP Core MVC Scaffolding SelectList (RC1) not populating dataget int value from XmlTextAttribute when deserialize xml to class in c#C# & XAML - Display JSON in ListView from Wunderground API






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









2


















I'm using vs2017 with entityframework 6.1.0 and winforms . As for entityframework i use code-first. I need to make a movie app, I have made all classes for them Movie, Genre and Cast(actors).
All Genres are pre inserted in the database. When using update-database everything is created including joining tables moviegenre and movie cast and also foreignkeys. When i insert a movie object. it links the id's from genre cast and movies but it also reinserts every genre which means i have duplicates. I only want the linking of course. So far this is my code.



movie class:



public class Movie

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

//[ForeignKey("GenreId")]
public virtual List<Genre> Genre get; set;

//[ForeignKey("CastId")]
public virtual List<Cast> cast get; set;

[Required]
public int GenreId get; set;

[Required]
public int CastId get; set;

[Display(Name = "Release Date")]
public DateTime ReleaseDate get; set;

public Movie()

Genre = new List<Genre>();
cast = new List<Cast>();




Genre and cast (the same for both classes)



public class Genre

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GenreId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

public List<Movie> Movies get; set;



and of course my code (this piece of code is from the button click event to add a movie into the db.):



private void btnAddMovie_Click(object sender, EventArgs e)

List<Genre> genrelist = new List<Genre>();
List<Cast> castlist = new List<Cast>();

var movie = new Movie();


movie.Name = txtTitle.Text;
movie.ReleaseDate = released;

//creating lists
foreach (string item in lbgenre2.Items)

var genre = new Genre();
genre.Name = item;
genrelist.Add(genre);


foreach (string item in lbCast2.Items)

var cast = new Cast();
cast.Name = item;
castlist.Add(cast);



movie.Genre = genrelist;
movie.cast = castlist;


_context.movies.Add(movie);

Save();


private async void Save()

await _context.SaveChangesAsync();



What am I doing wrong that it links and reinserts it?










share|improve this question



























  • you are creating the generes again, do you want to create generes in the movie add? or all the generes are already created?

    – Juan Salvador Portugal
    Mar 28 at 19:40











  • When inserting movies, do not create new Genre objects, but instead, query the genre list from the genre table, and assign that list to Movie.Genre.

    – mami
    Mar 28 at 19:46











  • yes the Genres are preinserted into the database. so i do _context.genres.tolist() into a alistbox. i select the Genres from that specific movie and place them in another listbox and i create the list from that second listbox

    – Tim Clinckemalie
    Mar 28 at 20:54

















2


















I'm using vs2017 with entityframework 6.1.0 and winforms . As for entityframework i use code-first. I need to make a movie app, I have made all classes for them Movie, Genre and Cast(actors).
All Genres are pre inserted in the database. When using update-database everything is created including joining tables moviegenre and movie cast and also foreignkeys. When i insert a movie object. it links the id's from genre cast and movies but it also reinserts every genre which means i have duplicates. I only want the linking of course. So far this is my code.



movie class:



public class Movie

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

//[ForeignKey("GenreId")]
public virtual List<Genre> Genre get; set;

//[ForeignKey("CastId")]
public virtual List<Cast> cast get; set;

[Required]
public int GenreId get; set;

[Required]
public int CastId get; set;

[Display(Name = "Release Date")]
public DateTime ReleaseDate get; set;

public Movie()

Genre = new List<Genre>();
cast = new List<Cast>();




Genre and cast (the same for both classes)



public class Genre

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GenreId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

public List<Movie> Movies get; set;



and of course my code (this piece of code is from the button click event to add a movie into the db.):



private void btnAddMovie_Click(object sender, EventArgs e)

List<Genre> genrelist = new List<Genre>();
List<Cast> castlist = new List<Cast>();

var movie = new Movie();


movie.Name = txtTitle.Text;
movie.ReleaseDate = released;

//creating lists
foreach (string item in lbgenre2.Items)

var genre = new Genre();
genre.Name = item;
genrelist.Add(genre);


foreach (string item in lbCast2.Items)

var cast = new Cast();
cast.Name = item;
castlist.Add(cast);



movie.Genre = genrelist;
movie.cast = castlist;


_context.movies.Add(movie);

Save();


private async void Save()

await _context.SaveChangesAsync();



What am I doing wrong that it links and reinserts it?










share|improve this question



























  • you are creating the generes again, do you want to create generes in the movie add? or all the generes are already created?

    – Juan Salvador Portugal
    Mar 28 at 19:40











  • When inserting movies, do not create new Genre objects, but instead, query the genre list from the genre table, and assign that list to Movie.Genre.

    – mami
    Mar 28 at 19:46











  • yes the Genres are preinserted into the database. so i do _context.genres.tolist() into a alistbox. i select the Genres from that specific movie and place them in another listbox and i create the list from that second listbox

    – Tim Clinckemalie
    Mar 28 at 20:54













2













2









2








I'm using vs2017 with entityframework 6.1.0 and winforms . As for entityframework i use code-first. I need to make a movie app, I have made all classes for them Movie, Genre and Cast(actors).
All Genres are pre inserted in the database. When using update-database everything is created including joining tables moviegenre and movie cast and also foreignkeys. When i insert a movie object. it links the id's from genre cast and movies but it also reinserts every genre which means i have duplicates. I only want the linking of course. So far this is my code.



movie class:



public class Movie

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

//[ForeignKey("GenreId")]
public virtual List<Genre> Genre get; set;

//[ForeignKey("CastId")]
public virtual List<Cast> cast get; set;

[Required]
public int GenreId get; set;

[Required]
public int CastId get; set;

[Display(Name = "Release Date")]
public DateTime ReleaseDate get; set;

public Movie()

Genre = new List<Genre>();
cast = new List<Cast>();




Genre and cast (the same for both classes)



public class Genre

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GenreId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

public List<Movie> Movies get; set;



and of course my code (this piece of code is from the button click event to add a movie into the db.):



private void btnAddMovie_Click(object sender, EventArgs e)

List<Genre> genrelist = new List<Genre>();
List<Cast> castlist = new List<Cast>();

var movie = new Movie();


movie.Name = txtTitle.Text;
movie.ReleaseDate = released;

//creating lists
foreach (string item in lbgenre2.Items)

var genre = new Genre();
genre.Name = item;
genrelist.Add(genre);


foreach (string item in lbCast2.Items)

var cast = new Cast();
cast.Name = item;
castlist.Add(cast);



movie.Genre = genrelist;
movie.cast = castlist;


_context.movies.Add(movie);

Save();


private async void Save()

await _context.SaveChangesAsync();



What am I doing wrong that it links and reinserts it?










share|improve this question
















I'm using vs2017 with entityframework 6.1.0 and winforms . As for entityframework i use code-first. I need to make a movie app, I have made all classes for them Movie, Genre and Cast(actors).
All Genres are pre inserted in the database. When using update-database everything is created including joining tables moviegenre and movie cast and also foreignkeys. When i insert a movie object. it links the id's from genre cast and movies but it also reinserts every genre which means i have duplicates. I only want the linking of course. So far this is my code.



movie class:



public class Movie

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int MovieId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

//[ForeignKey("GenreId")]
public virtual List<Genre> Genre get; set;

//[ForeignKey("CastId")]
public virtual List<Cast> cast get; set;

[Required]
public int GenreId get; set;

[Required]
public int CastId get; set;

[Display(Name = "Release Date")]
public DateTime ReleaseDate get; set;

public Movie()

Genre = new List<Genre>();
cast = new List<Cast>();




Genre and cast (the same for both classes)



public class Genre

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int GenreId get; set;

[Required]
[StringLength(255)]
public string Name get; set;

public List<Movie> Movies get; set;



and of course my code (this piece of code is from the button click event to add a movie into the db.):



private void btnAddMovie_Click(object sender, EventArgs e)

List<Genre> genrelist = new List<Genre>();
List<Cast> castlist = new List<Cast>();

var movie = new Movie();


movie.Name = txtTitle.Text;
movie.ReleaseDate = released;

//creating lists
foreach (string item in lbgenre2.Items)

var genre = new Genre();
genre.Name = item;
genrelist.Add(genre);


foreach (string item in lbCast2.Items)

var cast = new Cast();
cast.Name = item;
castlist.Add(cast);



movie.Genre = genrelist;
movie.cast = castlist;


_context.movies.Add(movie);

Save();


private async void Save()

await _context.SaveChangesAsync();



What am I doing wrong that it links and reinserts it?







c# .net winforms entity-framework-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 22:03









ingvar

2,7852 gold badges7 silver badges19 bronze badges




2,7852 gold badges7 silver badges19 bronze badges










asked Mar 28 at 19:31









Tim ClinckemalieTim Clinckemalie

991 silver badge7 bronze badges




991 silver badge7 bronze badges















  • you are creating the generes again, do you want to create generes in the movie add? or all the generes are already created?

    – Juan Salvador Portugal
    Mar 28 at 19:40











  • When inserting movies, do not create new Genre objects, but instead, query the genre list from the genre table, and assign that list to Movie.Genre.

    – mami
    Mar 28 at 19:46











  • yes the Genres are preinserted into the database. so i do _context.genres.tolist() into a alistbox. i select the Genres from that specific movie and place them in another listbox and i create the list from that second listbox

    – Tim Clinckemalie
    Mar 28 at 20:54

















  • you are creating the generes again, do you want to create generes in the movie add? or all the generes are already created?

    – Juan Salvador Portugal
    Mar 28 at 19:40











  • When inserting movies, do not create new Genre objects, but instead, query the genre list from the genre table, and assign that list to Movie.Genre.

    – mami
    Mar 28 at 19:46











  • yes the Genres are preinserted into the database. so i do _context.genres.tolist() into a alistbox. i select the Genres from that specific movie and place them in another listbox and i create the list from that second listbox

    – Tim Clinckemalie
    Mar 28 at 20:54
















you are creating the generes again, do you want to create generes in the movie add? or all the generes are already created?

– Juan Salvador Portugal
Mar 28 at 19:40





you are creating the generes again, do you want to create generes in the movie add? or all the generes are already created?

– Juan Salvador Portugal
Mar 28 at 19:40













When inserting movies, do not create new Genre objects, but instead, query the genre list from the genre table, and assign that list to Movie.Genre.

– mami
Mar 28 at 19:46





When inserting movies, do not create new Genre objects, but instead, query the genre list from the genre table, and assign that list to Movie.Genre.

– mami
Mar 28 at 19:46













yes the Genres are preinserted into the database. so i do _context.genres.tolist() into a alistbox. i select the Genres from that specific movie and place them in another listbox and i create the list from that second listbox

– Tim Clinckemalie
Mar 28 at 20:54





yes the Genres are preinserted into the database. so i do _context.genres.tolist() into a alistbox. i select the Genres from that specific movie and place them in another listbox and i create the list from that second listbox

– Tim Clinckemalie
Mar 28 at 20:54












2 Answers
2






active

oldest

votes


















1



















Your problem is because you are creating the Generes again, and again every time you add a new movie and you have a Identity Key, so, no exception will throw.



foreach (string item in lbgenre2.Items)

//Here is your problem, you are creating a new Genere instead of using the already created
var genre = new Genre();
genre.Name = item;
genrelist.Add(genre);



So, instead of creating, use ef to get the existing ones



foreach (string item in lbgenre2.Items)

//try to get the genere from database
var genre = _context.generes.FirstOrDefault(x => x.Name == item);
//if it doesn't exist..
if(genre == null)

//Create it
genre = new Genre();
//And set the name
genre.Name = item;

//but, if it already exist, you dont create a new one, just use the existing one
genrelist.Add(genre);






share|improve this answer



































    1



















    Entity Framework cannot figure out if a Genre or Cast already exists, even if you make an instance of one of them, with identical properties to one which exists in the database. Instead you need to get the existing genres and cast from the database and apply them. And only create a new instance, if it is a completely new genre or cast, which is not in the database:



    Pseudo-code:



    SaveMovie(Movie movie)

    var existingGenres = GetGenresFromDatabase();
    var movieGenres = GetGenresFromListBox();

    foreach (var genre in movieGenres)

    if (genre in existingGenres)

    existingGenre = existingGenres.Where(genreId = genre.Id);
    movie.Genres.Add(existingGenre)

    else

    movies.Add(genre)



    dbcontext.Add(movie);
    dbcontext.SaveChanges();






    share|improve this answer





















    • 1





      Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

      – mami
      Mar 28 at 19:59











    • @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

      – Noceo
      Mar 28 at 20:01











    • inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

      – Tim Clinckemalie
      Mar 28 at 20:57












    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405539%2fduplicates-in-database%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown


























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1



















    Your problem is because you are creating the Generes again, and again every time you add a new movie and you have a Identity Key, so, no exception will throw.



    foreach (string item in lbgenre2.Items)

    //Here is your problem, you are creating a new Genere instead of using the already created
    var genre = new Genre();
    genre.Name = item;
    genrelist.Add(genre);



    So, instead of creating, use ef to get the existing ones



    foreach (string item in lbgenre2.Items)

    //try to get the genere from database
    var genre = _context.generes.FirstOrDefault(x => x.Name == item);
    //if it doesn't exist..
    if(genre == null)

    //Create it
    genre = new Genre();
    //And set the name
    genre.Name = item;

    //but, if it already exist, you dont create a new one, just use the existing one
    genrelist.Add(genre);






    share|improve this answer
































      1



















      Your problem is because you are creating the Generes again, and again every time you add a new movie and you have a Identity Key, so, no exception will throw.



      foreach (string item in lbgenre2.Items)

      //Here is your problem, you are creating a new Genere instead of using the already created
      var genre = new Genre();
      genre.Name = item;
      genrelist.Add(genre);



      So, instead of creating, use ef to get the existing ones



      foreach (string item in lbgenre2.Items)

      //try to get the genere from database
      var genre = _context.generes.FirstOrDefault(x => x.Name == item);
      //if it doesn't exist..
      if(genre == null)

      //Create it
      genre = new Genre();
      //And set the name
      genre.Name = item;

      //but, if it already exist, you dont create a new one, just use the existing one
      genrelist.Add(genre);






      share|improve this answer






























        1















        1











        1









        Your problem is because you are creating the Generes again, and again every time you add a new movie and you have a Identity Key, so, no exception will throw.



        foreach (string item in lbgenre2.Items)

        //Here is your problem, you are creating a new Genere instead of using the already created
        var genre = new Genre();
        genre.Name = item;
        genrelist.Add(genre);



        So, instead of creating, use ef to get the existing ones



        foreach (string item in lbgenre2.Items)

        //try to get the genere from database
        var genre = _context.generes.FirstOrDefault(x => x.Name == item);
        //if it doesn't exist..
        if(genre == null)

        //Create it
        genre = new Genre();
        //And set the name
        genre.Name = item;

        //but, if it already exist, you dont create a new one, just use the existing one
        genrelist.Add(genre);






        share|improve this answer
















        Your problem is because you are creating the Generes again, and again every time you add a new movie and you have a Identity Key, so, no exception will throw.



        foreach (string item in lbgenre2.Items)

        //Here is your problem, you are creating a new Genere instead of using the already created
        var genre = new Genre();
        genre.Name = item;
        genrelist.Add(genre);



        So, instead of creating, use ef to get the existing ones



        foreach (string item in lbgenre2.Items)

        //try to get the genere from database
        var genre = _context.generes.FirstOrDefault(x => x.Name == item);
        //if it doesn't exist..
        if(genre == null)

        //Create it
        genre = new Genre();
        //And set the name
        genre.Name = item;

        //but, if it already exist, you dont create a new one, just use the existing one
        genrelist.Add(genre);







        share|improve this answer















        share|improve this answer




        share|improve this answer








        edited Mar 30 at 3:40

























        answered Mar 28 at 19:46









        Juan Salvador PortugalJuan Salvador Portugal

        7312 gold badges10 silver badges21 bronze badges




        7312 gold badges10 silver badges21 bronze badges


























            1



















            Entity Framework cannot figure out if a Genre or Cast already exists, even if you make an instance of one of them, with identical properties to one which exists in the database. Instead you need to get the existing genres and cast from the database and apply them. And only create a new instance, if it is a completely new genre or cast, which is not in the database:



            Pseudo-code:



            SaveMovie(Movie movie)

            var existingGenres = GetGenresFromDatabase();
            var movieGenres = GetGenresFromListBox();

            foreach (var genre in movieGenres)

            if (genre in existingGenres)

            existingGenre = existingGenres.Where(genreId = genre.Id);
            movie.Genres.Add(existingGenre)

            else

            movies.Add(genre)



            dbcontext.Add(movie);
            dbcontext.SaveChanges();






            share|improve this answer





















            • 1





              Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

              – mami
              Mar 28 at 19:59











            • @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

              – Noceo
              Mar 28 at 20:01











            • inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

              – Tim Clinckemalie
              Mar 28 at 20:57















            1



















            Entity Framework cannot figure out if a Genre or Cast already exists, even if you make an instance of one of them, with identical properties to one which exists in the database. Instead you need to get the existing genres and cast from the database and apply them. And only create a new instance, if it is a completely new genre or cast, which is not in the database:



            Pseudo-code:



            SaveMovie(Movie movie)

            var existingGenres = GetGenresFromDatabase();
            var movieGenres = GetGenresFromListBox();

            foreach (var genre in movieGenres)

            if (genre in existingGenres)

            existingGenre = existingGenres.Where(genreId = genre.Id);
            movie.Genres.Add(existingGenre)

            else

            movies.Add(genre)



            dbcontext.Add(movie);
            dbcontext.SaveChanges();






            share|improve this answer





















            • 1





              Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

              – mami
              Mar 28 at 19:59











            • @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

              – Noceo
              Mar 28 at 20:01











            • inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

              – Tim Clinckemalie
              Mar 28 at 20:57













            1















            1











            1









            Entity Framework cannot figure out if a Genre or Cast already exists, even if you make an instance of one of them, with identical properties to one which exists in the database. Instead you need to get the existing genres and cast from the database and apply them. And only create a new instance, if it is a completely new genre or cast, which is not in the database:



            Pseudo-code:



            SaveMovie(Movie movie)

            var existingGenres = GetGenresFromDatabase();
            var movieGenres = GetGenresFromListBox();

            foreach (var genre in movieGenres)

            if (genre in existingGenres)

            existingGenre = existingGenres.Where(genreId = genre.Id);
            movie.Genres.Add(existingGenre)

            else

            movies.Add(genre)



            dbcontext.Add(movie);
            dbcontext.SaveChanges();






            share|improve this answer














            Entity Framework cannot figure out if a Genre or Cast already exists, even if you make an instance of one of them, with identical properties to one which exists in the database. Instead you need to get the existing genres and cast from the database and apply them. And only create a new instance, if it is a completely new genre or cast, which is not in the database:



            Pseudo-code:



            SaveMovie(Movie movie)

            var existingGenres = GetGenresFromDatabase();
            var movieGenres = GetGenresFromListBox();

            foreach (var genre in movieGenres)

            if (genre in existingGenres)

            existingGenre = existingGenres.Where(genreId = genre.Id);
            movie.Genres.Add(existingGenre)

            else

            movies.Add(genre)



            dbcontext.Add(movie);
            dbcontext.SaveChanges();







            share|improve this answer













            share|improve this answer




            share|improve this answer










            answered Mar 28 at 19:47









            NoceoNoceo

            1,7861 gold badge21 silver badges41 bronze badges




            1,7861 gold badge21 silver badges41 bronze badges










            • 1





              Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

              – mami
              Mar 28 at 19:59











            • @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

              – Noceo
              Mar 28 at 20:01











            • inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

              – Tim Clinckemalie
              Mar 28 at 20:57












            • 1





              Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

              – mami
              Mar 28 at 19:59











            • @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

              – Noceo
              Mar 28 at 20:01











            • inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

              – Tim Clinckemalie
              Mar 28 at 20:57







            1




            1





            Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

            – mami
            Mar 28 at 19:59





            Won't Where return an IQueryable that will not fit for Add, which is intended to add a single entity?

            – mami
            Mar 28 at 19:59













            @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

            – Noceo
            Mar 28 at 20:01





            @mami probably, that's why I captioned it "pseudo-code" :-). Ideally you would probably be looking for something like FirstOrDefaultAsync, or even making a separate method for getting existing genres.

            – Noceo
            Mar 28 at 20:01













            inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

            – Tim Clinckemalie
            Mar 28 at 20:57





            inserting is async just in case. but thx both will workj. I have made this project in asp.net mvc and mvvm but i didn't know what was wrong here

            – Tim Clinckemalie
            Mar 28 at 20:57


















            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55405539%2fduplicates-in-database%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown









            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript