I am trying to get a list of objects stored in the database through a foreach loop, here is my current code:
foreach (var i in ruleset)
{
var currentRule = Rule;
currentRule.OriginIP = i[0];
currentRule.DestinationIP = i[1];
currentRule.Protocol = (Protocol)Enum.Parse(typeof(Models.Protocol), i[2]);
currentRule.Ports = i[3];
_context.Rules.Add(currentRule);
Console.WriteLine(_context.ChangeTracker.DebugView.LongView);
Console.WriteLine(currentRule.RuleID);
}
_context.SaveChanges();
For some reason this only actually stores the last object in the list, I have SaveChanges() outside of the loop as I assumed that would increase performance.
When I run this I get the following:
rule {RuleID: -2147482647} Added
RuleID: -2147482647 PK Temporary
CreationDate: '26/01/2021 14:16:10'
DestinationIP: '10.232.20.20'
Enabled: 'False'
OriginIP: '192.168.10.10'
Ports: '80, 443'
Protocol: 'TCP'
0
rule {RuleID: -2147482647} Added
RuleID: -2147482647 PK Temporary
CreationDate: '26/01/2021 14:16:10'
DestinationIP: '10.232.20.21' Originally '10.232.20.20'
Enabled: 'False'
OriginIP: '192.168.10.11' Originally '192.168.10.10'
Ports: '80, 444' Originally '80, 443'
Protocol: 'TCP'
Seeing the ChangeTracker show a change for each entry, I tried to put SaveChanges() inside the loop, but then the first entry is stored and the second errors out since it attempts to use the same ID as the entry it has just saved:
rule {RuleID: -2147482647} Added
RuleID: -2147482647 PK Temporary
CreationDate: '26/01/2021 14:25:40'
DestinationIP: '10.232.20.20'
Enabled: 'False'
OriginIP: '192.168.10.10'
Ports: '80, 443'
Protocol: 'TCP'
62
rule {RuleID: 62} Added
RuleID: 62 PK
CreationDate: '26/01/2021 14:25:40'
DestinationIP: '10.232.20.21' Originally '10.232.20.20'
Enabled: 'False'
OriginIP: '192.168.10.11' Originally '192.168.10.10'
Ports: '80, 444' Originally '80, 443'
Protocol: 'TCP'
I know I must be doing something wrong but I can't find what!
question from:
https://stackoverflow.com/questions/65903212/dbcontext-failing-to-save-multiple-entries 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…