M
M
mindgrow2021-10-12 10:03:25
ASP.NET
mindgrow, 2021-10-12 10:03:25

How to update without creating related data of the added entity when joining ManyToMany (EF CORE 5)?

Good afternoon!

There is an Event entity that can be associated with the Tag set through the Tags field. One Tag can be associated with multiple Events.

When saving an Event that contains tags that have already been created, an error occurs:

SqlException: Violation of PRIMARY KEY constraint 'PK_Tags'. Cannot insert duplicate key in object 'dbo.Tags'. The duplicate key value is (asdasdffads). The statement has been terminated.


What am I doing wrong and how can I fix it?
I'm using EF Core 5

Entities
public  class Event
{
[Key]
public long EventId {get;set;]
public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
[Key]
public string Title {get;set;}
public virtual ICollection<Event> Events { get; set; }
}


fluent API
modelBuilder.Entity<Event>()
                .HasMany(e => e.Tags)
                .WithMany(e => e.Events);


Create/Save
Event eventDT = _mapper.Map<Event>(eventVM);
                eventDT.CreatedDate = DateTime.Now;
                eventDT.CreatorId = _httpContextAccessor.GetUsername();

                _db.Events.Add(eventDT);                
                _db.SaveChanges();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Golets, 2021-10-29
@igolets

I'm afraid I'll have to run to the database and get the database objects for those tags that are already in the database. Either save through storage and check in it whether there is such a tag in the database or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question