B
B
bizir2019-11-13 11:18:44
C++ / C#
bizir, 2019-11-13 11:18:44

ENTITY FRAMEWORK Fluent API how to prevent creating a record if it already exists?

There are 2 tables with many to many relationship

public class Movie
    {
        [Key]
        public int MovieId{ get; set; }
        [MaxLength(100)]
        public string Title{ get; set; }
        public List<Country> Countrys{ get; set; }
    }
    public class Country
    {
        [Key]
        public int CountryId { get; set; }
        [MaxLength(10)]
        public string Key { get; set; }
        public List<Movie> Movies { get; set; }
    }

Tethered them to each other via Fluent API like this
modelBuilder.Entity<Cinema_Country>()
                .HasMany(c => c.Movies)
                .WithMany(c => c.Countrys)
                .Map(c =>
                {
                    c.ToTable("Cinema_CountryMovie");
                    c.MapRightKey("MovieId");
                    c.MapLeftKey("CountryId");
                });

But when you add the Country table to the Movie table and save the . Another entry is created in Country. How to forbid to add records to this table if record already exists?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2019-11-13
@bizir

This is because the EF change tracker does not have Country information at the time of saving.
You need to "attach" existing countries to the context before saving. Here is an example in the official docs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question