gpt4 book ai didi

c# - 多对多自引用关系

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:39 24 4
gpt4 key购买 nike

我是 EF 的新手。我遇到了创建多对多自引用关系的问题。我尝试使用以下解决方案:Entity Framework Core: many-to-many relationship with same entity

我的实体:

public class WordEntity
{
public long Id { get; set; }
public string Name { get; set; }
public string Json { get; set; }

public virtual List<WordSinonymEntity> Sinonyms { get; set; }
}


public class WordSinonymEntity
{
public long WordId { get; set; }
public virtual WordEntity Word { get; set; }

public long SinonymId { get; set; }
public virtual WordEntity Sinonym { get; set; }
}

和下一个配置:

 modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Sinonym)
.WithMany(p => p.Sinonyms)
.HasForeignKey(pt => pt.SinonymId);

modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Word)
.WithMany(t => t.Sinonyms)
.HasForeignKey(pt => pt.WordId);`

但它会导致下一个异常。

System.InvalidOperationException: 'Cannot create a relationship between 'WordEntity.Sinonyms' and 'WordSinonymEntity.Word', because there already is a relationship between 'WordEntity.Sinonyms' and 'WordSinonymEntity.Sinonym'. Navigation properties can only participate in a single relationship.'

有没有人可以帮助我或者建议一些例子来学习?谢谢。

最佳答案

您关注的帖子绝对是错误的。

每个集合或引用导航属性只能成为单个关系的一部分。虽然与显式连接实体的多对多关系是通过两个一对多关系实现的。连接实体包含两个引用导航属性,但主实体只有单个集合导航属性,它必须与其中之一相关联,但不能与两者相关联。

解决该问题的一种方法是添加第二个集合导航属性:

public class WordEntity
{
public long Id { get; set; }
public string Name { get; set; }
public string Json { get; set; }

public virtual List<WordSinonymEntity> Sinonyms { get; set; }
public virtual List<WordSinonymEntity> SinonymOf { get; set; } // <--
}

并通过 Fluent API 指定关联:

modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Sinonym)
.WithMany(p => p.SinonymOf) // <--
.HasForeignKey(pt => pt.SinonymId)
.OnDelete(DeleteBehavior.Restrict); // see the note at the end

modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Word)
.WithMany(t => t.Sinonyms)
.HasForeignKey(pt => pt.WordId);

另一种方法是保持模型不变,但将 WordSinonymEntity.Sinonym 映射到单向 关联(具有引用导航属性但没有相应的集合导航属性):

modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Sinonym)
.WithMany() // <--
.HasForeignKey(pt => pt.SinonymId)
.OnDelete(DeleteBehavior.Restrict); // see the note at the end

modelBuilder.Entity<WordSinonymEntity>()
.HasOne(pt => pt.Word)
.WithMany(t => t.Sinonyms)
.HasForeignKey(pt => pt.WordId);

只需确保 WithMany 与相应导航属性的存在/不存在完全匹配。

请注意,在这两种情况下,您都必须为至少一种关系关闭删除级联,并在删除主要实体之前手动删除相关的连接实体,因为自引用关系总是引入可能的循环或多重级联路径问题,阻止级联删除的使用。

关于c# - 多对多自引用关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58834609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com