I have the following structure and am using Entity Framework 6.2:
public class MainModel
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
public ModelB ModelB { get; set; }
public ModelC ModelC { get; set; }
}
public class ModelB
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
public Account Account { get; set; }
}
public class ModelC
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
public Account Account { get; set; }
}
public class Account
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long Id { get; set; }
public string Description { get; set; }
}
I don't want SQL to assign PK automatically as these are entities that will already have a unique id (ex. there is only ever 1 account with Id 2, etc..)
When I try to run the following, I get a private key violation Cannot insert duplicate key in object dbo.Account
. The duplicate key value is (2).
var context = new MyContext();
myOrders.ToList().ForEach(p =>
{
context.MyOrders.AddOrUpdate(p);
});
context.SaveChanges();
I've tried AsNoTracking()
and setting the EntityState
to Modified
if it's found in the table already.
This is the JSON data that is populating myOrders. myOrders is a List
[ {
"MainModel": {
"Id": 100,
"ModelB": {
"Id": 1,
"Account": {
"Id": 2,
"Description":"This is a test account"
}
},
"ModelC": {
"Id": 1,
"Account": {
"Id": 2,
"Description":"This is a test account"
}
}
}
},
{
"MainModel": {
"Id": 200,
"ModelB": {
"Id": 5,
"Account": {
"Id": 2,
"Description":"This is a test account"
},
}
"ModelC": {
"Id": 6,
"Account": {
"Id": 2,
"Description":"This is a test account"
}
}
}
}
}
]
Any thoughts?