Adding association (link table record) without creating a new related record.
I have two tables Products and Categories with a many to many relationship. I am trying to copy the categories linked to one product (OriginalProduct) to another product (newProduct). The problem is when I execute the SaveChanges()
method, I not only get the records in my linking table, but it also creates another copy of the categories in the categories table. I've tried this in many ways but here are the last couple that I've attempted:
' Copy Product/Categories
For Each oneProdCategory In Orig开发者_如何学编程inalProduct.Categories
Dim relatedCategory = _productContext.GetObjectByKey(New EntityKey ("ProductInfoEntities.Categories", "RecordId", oneProdCategory.RecordId))
Dim newCategory As New Category
With newCategory
.Description = relatedCategory.Description
.isActive = relatedCategory.IsActive
.RecordId = relatedCategory.RecordId
End With
newProduct.Categories.Add(newCategory)
Next
This attempt results in both linking table records being created (which is good) but is also creates copies of all the categories as well (not so good)
' Copy Product/Categories
For Each oneProdCategory In OriginalProduct.Categories
Dim relatedCategory = _productContext.GetObjectByKey(New EntityKey ("ProductInfoEntities.Categories", "RecordId", oneProdCategory.RecordId))
newProduct.Categories.Add(relatedCategory)
Next
This results in the following error:
"An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
Edit
For Each oneProdCategory In OriginalProduct.Categories
newProduct.Categories.Add(oneProdCategory)
Next
Private Sub tsBtnSave_Click(sender As System.Object, e As System.EventArgs) Handles tsBtnSave.Click
_productContext.SaveChanges()
If _formMode = DataFormAction.Insert Or _formMode = DataFormAction.Duplicate Then
Me.Close()
End If
End Sub
You can try
newProduct.Categories.AddRange(OriginalProduct.Categories)
If your Categories
property is a List
OR
For Each oneProdCategory In OriginalProduct.Categories
newProduct.Categories.Add(oneProdCategory)
Next
Make sure all the entities are retrieved, created with the same context.
精彩评论