我有一个请求表(EF 生成):
public class Request
{
public int Id { get; set; }
public string Name {get; set; }
public virtual ICollection<AttendeeRequest> AttendeeRequests { get; } = new List<AttendeeRequest>();
}
我还有一个与会者表格(EF 生成):
public class Attendee
{
public int Id { get; set;}
public string Name { get; set; }
public virtual ICollection<AttendeeRequest> AttendeeRequests { get; } = new List<AttendeeRequest>();
}
我还有他们的多对多表(EF 生成):
public class AttendeeRequest
{
public int Id { get; set; }
public int RequestId { get; set;}
public int AttendeeId { get; set; }
}
我的任务是将请求插入与参加者相关的数据库中。 我创建一个事务,将请求插入数据库,然后将与会者插入数据库,然后,对于他们的关系,我这样做:
foreach (var attendee in attendees)
{
var manyToManyRelationRecord = new AttendeeRequest()
{
AttendeeId = attendee.Id,
RequestId = requestToInsert.Id //this is the already inserted request, so it is going to have an ID
};
//Save changes code here
}
这可行,但对我来说似乎很“手动”。 EF 不能自动处理此插入吗?你会如何解决这个问题?
您可以在
OnModelCreating
中为 EF 提供显式连接表名称。
这应该避免在您的
foreach
中手动设置连接表 ID。
尝试以下操作:
public class Request
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Attendee> Attendees { get; set; }
}
public class Attendee
{
public int Id { get; set;}
public string Name { get; set; }
public virtual ICollection<Request> Requests { get; set; }
}
public class AttendeeRequest
{
public int Id { get; set; }
public int RequestId { get; set;}
public int AttendeeId { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Request>()
.HasMany(e => e.Attendees )
.WithMany(e => e.Requests )
.UsingEntity("AttendeeRequest");
}