Answer the question
In order to leave comments, you need to log in
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.
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; }
}
modelBuilder.Entity<Event>()
.HasMany(e => e.Tags)
.WithMany(e => e.Events);
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
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 questionAsk a Question
731 491 924 answers to any question