Reputation: 2921
I can't add a new instance of the type InventoryItem because ChangeTracker thinks I modified the primary key. But it is as the constructor done.
On the other hand, I could add items without problem. But when I inserted it after creation of an InventoryItemType (that is a NavigationProperty of InventoryItem) it fails.
I searched, tried, updated EF from 5 to 6.1.1 and I surrended... I need your help
InventoryItemType iit = new InventoryItemType
{
InventoryFamilyID = 12,
Name = checkInPackage.Name,
Provider = shippingDestination.RelatedWarehouse.Name,
Reference = "Paquete nº " + checkInPackage.CheckInPackageId
};
this.inventoryItemTypeRepository.InsertOrUpdate(iit);
this.inventoryItemTypeRepository.Save();
InventoryItem ii = new InventoryItem
{
WarehouseID = checkInPackage.WarehouseID,
Price = 0,
InventoryItemTypeID = iit.InventoryItemTypeID
};
this.inventoryItemRepository.InsertOrUpdate(ii); // th
this.inventoryItemRepository.Save();
The repository has:
public void InsertOrUpdate(InventoryItem inventoryitem)
{
if (inventoryitem.InventoryItemID == default(int)) {
// New entity
context.InventoryItems.Add(inventoryitem);
} else {
// Existing entity
context.Entry(inventoryitem).State = EntityState.Modified;
}
}
EDITED WITH THE FIX:
I had a bad definition about the relationship InventoryItemType
1 to InventoryItem
n
After doing this changes in InventoryItemType.cs it runs without errors:
public InventoryItemType()
{
InventoryItems = new HashSet<InventoryItem>();
}
public virtual ICollection<InventoryItem> InventoryItems { get; set; }
In business logic side
iit.InventoryItems.Add(
new InventoryItem
{
WarehouseID = checkInPackage.WarehouseID,
Price = 0,
InventoryItemType = iit
}
);
this.inventoryItemTypeRepository.InsertOrUpdate(iit);
this.inventoryItemTypeRepository.Save();
Upvotes: 0
Views: 576
Reputation: 11554
According to this description and this one, Instead of setting InventoryItemTypeID
set InventoryItemType
in InventoryItem
entity, maybe it works.
InventoryItem ii = new InventoryItem
{
WarehouseID = checkInPackage.WarehouseID,
Price = 0,
InventoryItemType = iit
};
Upvotes: 1