我面對的問題是,無論何時我調用events.Tags.Add(tag)並調用在上下文中保存更改,它最終會在Tags表中創建一個新的標記信息,而不僅僅是將EventId和TagId插入到EventTags表中。保存到多對多的關係
基於以下數據,我如何將事件和標籤添加到EventTags表中。比方說,我想添加Id = 2的事件,和Id = 1的標記到EventTags表。
我有以下實體。
public class Event
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class EventConfiguration : EntityTypeConfiguration<Event> {
public EventConfiguration() {
ToTable("Events");
HasKey(x => x.Id).Property(x => x.Id).HasColumnName("Id").IsRequired();
Property(x => x.Name).HasColumnName("Name").IsRequired();
HasMany(x => x.Tags)
.WithMany(x => x.Events)
.Map(m => {
m.ToTable("EventTags");
m.MapLeftKey("EventId");
m.MapRightKey("TagId");
});
}
}
public class TagConfiguration : EntityTypeConfiguration<Tag> {
public TagConfiguration() {
ToTable("Tags");
HasKey(x => x.Id).Property(x => x.Id).HasColumnName("Id").IsRequired();
Property(x => x.Name).HasColumnName("Name").IsRequired();
}
}
/*
These are the records in my many to many tables
--------------
Events Table
--------------
Id Name
1 Test1
2 Test2
--------------
EventTags
-------------
EventId TagId
1 2
-------------
Tags
------------
Id Name
1 MVC
2 C#
*/
發佈您的添加代碼 - 是您添加從相同的DBContext獲取的標籤嗎? – Andiih