I am adding EF6 and trying to recreate the model of my legacy db. I am also making a WCF web service. There are way too many fields, so I've minimized the example to better pinpoint the problem.
I am trying to enter some data into the database for an Order. The Order includes OrderLines and each OrderLine can have licenses. OrderLine is one to many on rare occasions so I have to do one to many. If one OrderLine and License is for a part, the next OrderLine and License is for Maintenance for that part. The part license must link to the maintenance license.
ParentLicenceId is the issue. In my legacy db, there is the relationship between one License and another License that is of PartType Maintenance. So if a customer buys Part X, they might by 1 year of maintenance for Part X. So the Part X Maintenance License will list the Part X license as it's parent.
using OrderExample;
using System;
using System.Collections.Generic;
namespace OrderExampleCmd
{
class Program
{
static void Main()
{
var omc = new OrderExampleEntities();
var order = new Order
{
OrderNumber = new Guid().ToString(),
OrderLines = new List<OrderLine>()
};
// Maitenance
var orderLine1 = new OrderLine
{
OrderLineNumber = 1,
Licenses = new List<License>()
};
var orderLine1License = new License
{
LicenseType = "Maintenance"
};
orderLine1.Licenses.Add(orderLine1License);
// Part
var orderLine2 = new OrderLine
{
OrderLineNumber = 2,
Licenses = new List<License>()
};
var orderLine2License = new License
{
LicenseType = "Part",
MaintenanceLicense = orderLine1License
};
orderLine1License.PartLicenses.Add(orderLine2License);
order.OrderLines.Add(orderLine1);
order.OrderLines.Add(orderLine2);
omc.Orders.Add(order);
omc.SaveChanges();
}
}
}
There error message occurs at omc.SaveChanges() and is this:
Unable to determine the principal end of the 'OrderExampleModel.LicenseParentLicense' relationship. Multiple added entities may have the same primary key.
I have tried:
I've gone through several other articles. I'm hoping there is just some advanced setting I need to apply.
How do I get past this error to save these changes?
The error is caused by temporary non unique primary keys detected in the attached entities. You need to assign temporary primary keys and foreign keys for order lines.
When a new entity is created, the Entity Framework defines temporary key and sets the IsTemporary property to true. When you call the SaveChanges method, the Entity Framework assigns a permanent key and sets the IsTemporary property to false. - MSDN
By default orderLine1
and orderLine2
have the same temporary primary keys that are 0 (default value of integer), you need to set them temporary to prevent 2 order lines have the same temporary id (that is 0).
orderLine1.OrderLineId = 1;
orderLine1License.OrderLineId = 1;
orderLine2.OrderLineId = 2;
orderLine2License.OrderLineId = 2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With