[英]DbContext failing to save multiple entries
我正在嘗試通過 foreach 循環獲取存儲在數據庫中的對象列表,這是我當前的代碼:
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();
由於某種原因,這實際上只存儲了列表中的最后一個 object,我在循環之外有 SaveChanges(),因為我認為這會提高性能。
當我運行它時,我得到以下信息:
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'
看到 ChangeTracker 顯示每個條目的更改,我嘗試將 SaveChanges() 放入循環中,但隨后第一個條目被存儲,第二個錯誤輸出,因為它嘗試使用與剛剛保存的條目相同的 ID:
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'
我知道我一定做錯了什么,但我找不到什么!
您一遍又一遍地添加相同的規則。 嘗試類似的東西
foreach (var i in ruleset)
{
var currentRule = new 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);
}
_context.SaveChanges();
var currentRule = Rule;
_context.Rules.Add(currentRule);
您一遍又一遍地添加相同的Rule
object。
當您向 EF 添加內容時,它會跟蹤 object。 這就是 EF 知道實體何時更新的方式。 EF 無法多次跟蹤相同的內存 object 並假裝它們不同。
第一次,您的實體被添加。
第二次,EF 意識到這與之前的 object 相同,因此沒有添加任何新內容 - 它已經在跟蹤這個 object。
確保添加新對象,例如:
var currentRule = new Rule();
// set some values
_context.Rules.Add(currentRule);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.