实体框架 - 许多多对多关系

发布于 2024-12-28 10:11:34 字数 125 浏览 1 评论 0原文

我正在尝试使用 EF 将产品与交易关联起来。目前,它只允许我将同一交易映射到产品一次。

例如,在交易中,尝试添加两个相同的产品是行不通的。它只会存储一个映射吗?

可以这样做吗?或者我应该创建一个解决方法?

I'm trying to use EF to relate products to transactions. Currently it allows me to only map the same transaction to on product only once.

For example, in a transaction, trying to add two of the same product doesn't work. It will only ever store one mapping?

Is it possible to do this? Or should I just create a workaround?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

琉璃繁缕 2025-01-04 10:11:34

EF 不允许您向多对多关系添加重复项。连接表应该只包含参与表的主键作为表的主键。

您可以通过将连接表映射为实体并创建一个自动递增的 id 作为连接表的 PK 来解决此问题。

public class ProductTransaction
{
    [Key]
    public int Id { get; set; }

    public int ProductId { get; set; }

    public int TransactionId { get; set; }

    public Product Product { get; set; }

    public Transaction Transaction { get; set; }
}

public class Product
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<ProductTransaction> Transactions { get; set; }
}

public class Transaction
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<ProductTransaction> Products { get; set; }
}

EF does not allow you to add duplicates to the many to many relationships. The join table should only contain the primary keys of the participating tables as the PK of the table.

You can workaround this problem by mapping the join table as an entity and creating an auto incremented id as the PK of the join table.

public class ProductTransaction
{
    [Key]
    public int Id { get; set; }

    public int ProductId { get; set; }

    public int TransactionId { get; set; }

    public Product Product { get; set; }

    public Transaction Transaction { get; set; }
}

public class Product
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<ProductTransaction> Transactions { get; set; }
}

public class Transaction
{
    [Key]
    public int Id { get; set; }

    public virtual ICollection<ProductTransaction> Products { get; set; }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文