在EF Core 3.1.3中,可以使用以下步骤来保存多对多关系中的更改:
以下是一个示例代码,演示如何在多对多关系中保存更改:
// 定义连接表实体对象
public class Relationship
{
public int Entity1Id { get; set; }
public int Entity2Id { get; set; }
public virtual Entity1 Entity1 { get; set; }
public virtual Entity2 Entity2 { get; set; }
}
// 定义相关实体对象
public class Entity1
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Entity1")]
public virtual ICollection<Relationship> Relationships { get; set; }
}
public class Entity2
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("Entity2")]
public virtual ICollection<Relationship> Relationships { get; set; }
}
// 在DbContext中添加DbSet和连接表实体集合
public class MyDbContext : DbContext
{
public DbSet<Entity1> Entity1s { get; set; }
public DbSet<Entity2> Entity2s { get; set; }
public DbSet<Relationship> Relationships { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Relationship>()
.HasKey(r => new { r.Entity1Id, r.Entity2Id });
modelBuilder.Entity<Relationship>()
.HasOne(r => r.Entity1)
.WithMany(e => e.Relationships)
.HasForeignKey(r => r.Entity1Id);
modelBuilder.Entity<Relationship>()
.HasOne(r => r.Entity2)
.WithMany(e => e.Relationships)
.HasForeignKey(r => r.Entity2Id);
}
}
// 在保存更改时创建连接表实体对象并添加到DbContext中
using (var context = new MyDbContext())
{
var entity1 = new Entity1 { Name = "Entity 1" };
var entity2 = new Entity2 { Name = "Entity 2" };
context.Entity1s.Add(entity1);
context.Entity2s.Add(entity2);
var relationship = new Relationship
{
Entity1 = entity1,
Entity2 = entity2
};
context.Relationships.Add(relationship);
context.SaveChanges();
}
这样,EF Core 3.1.3会自动处理多对多关系的保存和更新。在这个示例中,我们创建了一个连接表实体对象Relationship,表示Entity1和Entity2之间的多对多关系。通过添加Relationship对象到DbContext的Relationships集合中,EF Core会自动保存这个多对多关系的更改。
领取专属 10元无门槛券
手把手带您无忧上云