EF Core:同一张表上的多对多关系

huangapple go评论60阅读模式
英文:

EF Core: A many to many relationship on the same table

问题

你好,以下是代码的翻译部分:

public class Produto
{
    [Key]
    public int Id { get; set; }
    public string Nome { get; set; } = String.Empty;
    //其他内容
    public ICollection<Produto>? ProdutosRelacionados { get; set; }
}

你提到有一个名为 "Produto" 的表,其中有许多相关的产品。你想知道如何在 Fluent API 中实现它。

我尝试手动配置一个关联表,但 EF Core 不允许我进行迁移。你不能为同一张表创建一个具有两个外键的类。

英文:

Let's say I have this class:

    public class Produto
    {
        [Key]
        public int Id { get; set; }
        public string Nome { get; set; } = String.Empty;
//other stuff
        public ICollection&lt;Produto&gt;? ProdutosRelacionados { get; set; }
    }

I have a table "Produto" that has many "Produto" (related products, as in every e-commerce)
How do I implement it in the fluent API?
Thanks

I tried to manualy configure a link table. EF core does not let me do the migration. You cannot create a class with two forigner keys for the same table...

答案1

得分: 0

我找到了一个解决方案。你必须配置双向导航,所以你必须创建另一个属性:

...

public ICollection<Produto>? ProdutoPai{ get; set; }

...

然后在 fluent API 中进行配置:

...

builder.Entity<Produto>(ent => {
    //其他实体配置...
    ent.HasMany(p => p.ProdutosRelacionados)
    .WithMany(p => p.ProdutoPai)
    .UsingEntity(j => j.ToTable("ProdutosRelacionados"));
});
英文:

I found a solution. You MUST configure a two way navigation, so you have to create another property

...

public ICollection&lt;Produto&gt;? ProdutoPai{ get; set; }

...

And then configure it on the fluent API like so

...

builder.Entity&lt;Produto&gt;(ent =&gt; {
//outras configs da entidade...
ent.HasMany(p =&gt; p.ProdutosRelacionados)
.WithMany(p =&gt; p.ProdutoPai)
.UsingEntity(j =&gt; j.ToTable(&quot;ProdutosRelacionados&quot;));
});

...

huangapple
  • 本文由 发表于 2023年6月6日 05:30:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定