Mikkel
Mikkel

Reputation: 1811

Entity framework keeps inserting duplicate objects when adding

I could really need some help in order to solve this issue. When I try to add an entity using Entity Framework, it keeps adding 1 more than needed.

Here you see my database after I have added 2 movies.

enter image description here

As you see, it adds the same movie "The rock" twice.

Been looking into the problem the past two days, but haven't found a solution that don't giving my exceptions.

Code:

public bool Execute(RequestedMovie movie)
    {
        using (var context = new MoviesContext())
        {
            context.RMovies.Attach(movie);
            context.RMovies.Add(movie);
            context.SaveChanges();
        }

        return true;

    }

Model:

public class RequestedMovie
{
    [Key]
    public int RequestedMoviesID { get; set; }
    public string MovieId { get; set; }
    public string MovieTitle { get; set; }
    public string MovieLink { get; set; }
    public string MovieYear { get; set; }
    public int MovieQuality { get; set; }
    public string Requester { get; set; }
    public bool Status { get; set; }

}

DataContext:

public class MoviesContext : DbContext, IMoviesContext
{
    public MoviesContext() : base("MoviesContext")
    {

    }

    // DbSet to bookings
    public DbSet<Movie> Movies { get; set; }
    public DbSet<RequestedMovie> RMovies { get; set; }

    public void MarkAsAdded(Movie item)
    {
        Entry(item).State = EntityState.Added;
    }

    public void MarkAsDeleted(Movie item)
    {
        Entry(item).State = EntityState.Deleted;
    }

    public void MarkRequestedMovieAsAdded(RequestedMovie item)
    {
        Entry(item).State = EntityState.Added;
    }

    public void MarkRequestedMovieAsModified(RequestedMovie item)
    {
        Entry(item).State = EntityState.Modified;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    }
}

This should be pretty strait forward, because I only have one table which I'm going to add to. Have tried with the Attach approach that I found in another Stack post, but it still won't work :(.

Have also tried using the methods (MarkRequestedMovieAsAdded) I have in my context file, instead of RMovies.Add(objekt), but same result.

What could be wrong here?

Upvotes: 1

Views: 337

Answers (2)

Mikkel
Mikkel

Reputation: 1811

I managed to solve this issue. I haven't done any mistake in the Web Api. It turned out that my Angular2 observable calls made an error and called my web api twice because it was (cold) and not (warm).

Here is the post about it: Angular2 http.post gets executed twice

All I should do was add .share() after mapping in my angular2 service.

Upvotes: 0

ErikEJ
ErikEJ

Reputation: 41749

Just use:

    context.RMovies.Add(movie);
    context.SaveChanges();

Upvotes: 1

Related Questions