Jefim
Jefim

Reputation: 3077

Entity Framework - adding the same entity twice in many-to-many relationships

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.

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!

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?

Upvotes: 2

Views: 2433

Answers (2)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

In the second add statement it will not add another object because part is already in added state. So you need to create a new object with same properties add it again.

product.Parts.Add(new Part{someProperty=part.someProperty ... ect });

if you want to reduce code you can use Automapper ( http://automapper.codeplex.com/ )to copy all properties,

 product.Parts.Add(Mapper.Map<Part,Part>(part));

Upvotes: 0

Akash Kava
Akash Kava

Reputation: 39916

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.

Upvotes: 3

Related Questions