我面临的问题是,无论何时我调用events.Tags.Add(tag)并在上下文中调用Save changes,它最终会在Tags表中创建一个新的标签信息,而不是仅仅将EventId和TagId插入到EventTags表。
根据以下数据,如何将事件和标记添加到EventTags表中。假设我想在事件标记表中添加Id = 2的事件和ID = 1的标记。
我有以下实体。
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#
*/
答案 0 :(得分:0)
假设我想添加Id = 2的事件和ID为Id = 1的标签 EventTags表。
using (var context = new MyContext())
{
// Load the event
var theEvent = context.Events.Find(2);
// Load the tag
var theTag = context.Tags.Find(1);
// Add tag to Tags collection of the event
theEvent.Tags.Add(theTag);
// Save
context.SaveChanges();
}
这足以更新两个集合中的一个。 EF会自动处理其他收藏。
修改强>
如果您知道现有的ID,则不从数据库加载实体的另一个选项:
using (var context = new MyContext())
{
// Create an event with Id 2
var theEvent = new Event { Id = 2, Tags = new HashSet<Tag>() };
// Create a tag with Id 1
var theTag = new Tag { Id = 1 };
// Attach both event and tag to the context
context.Events.Attach(theEvent);
context.Tags.Attach(theTag);
// Add tag to Tags collection of the event
theEvent.Tags.Add(theTag);
// Save
context.SaveChanges();
}
您还可以混合使用这两种方法,例如从DB加载事件,创建并附加标记。