实体框架 - 在多对多关系中添加相同的实体两次 [英] Entity Framework - adding the same entity twice in many-to-many relationships

查看:118
本文介绍了实体框架 - 在多对多关系中添加相同的实体两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定。所以这里是交易。我有两个实体 - 产品和零件。产品由零件组成。零件在其他产品中可重复使用。这些实体之间的关系是多对多的。这一切都很好。

Ok. So here is the deal. I have two entities - "Product" and "Parts". The product consists of parts. And parts are reusable in other products. The relation between those entities is many-to-many. And it all works great.

问题是,我无法将相同的产品添加到同一个产品两次。 EF似乎强制所有相关实体是独一无二的。请考虑以下代码:

The problem is that I cannot add the same part to the same product twice. EF seems to force all the related entities to be unique. Consider the following code:

var product = context.Create<Product>();
var part = GetSomePart();

Console.WriteLine(product.Parts.Count); // will output 0

// Add a part
product.Parts.Add(part);
Console.WriteLine(product.Parts.Count); // will output 1

// Add the same part again
product.Parts.Add(part);
Console.WriteLine(product.Parts.Count); // will output 1!

好的,我得到点 - 避免重复或某事。但我需要这样做才是可能的。有没有办法这样做(告诉EF停止执行唯一值),而不创建额外的表?或者是解决这个问题的唯一方法是手动添加中间表并处理多对多自己?

So ok, I get the point - avoid duplicates or something. But I need this to be possible. Is there a way to do this (to tell EF to stop enforcing unique values) without creating an additional table? Or is the only way to resolve this is to manually add the intermediate table and handle the many-to-many myself?

推荐答案

在这种情况下,您将不得不创建另一个名为ProductParts的表,该表将具有身份唯一的密钥,并且可以保存对产品和部件的引用,并且它们也可以是多个。

In this case you will have to create another table called "ProductParts" which will have an identity unique key, and which can hold references to both product and part, and they can be multiple too.

这篇关于实体框架 - 在多对多关系中添加相同的实体两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆