我遇到了插入或更新約950個實體的問題。實體框架Core1.1 - 大容量插入或更新 - InvalidOperationException
var coins = JsonConvert.DeserializeObject<List<Currency>>(json);
var sw = new Stopwatch();
sw.Start();
using (var ctx = CryptoContext.Get)
{
var existingCoins = ctx.Coins.ToList();
foreach (var coin in coins)
{
var existing = existingCoins.FirstOrDefault(c => c.CMC_Id == coin.CMC_Id);
if (existing != null)
{
ctx.Entry<Currency>(coin).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
} else
{
ctx.Entry<Currency>(coin).State = Microsoft.EntityFrameworkCore.EntityState.Added;
}
}
ctx.SaveChanges();
var el = sw.ElapsedMilliseconds;
}
的代碼運行在我netcoreapp1.1的背景下,使用SQLite,並檢索貨幣的列表。 FluentScheduler每5分鐘完成一次。因爲它們不是完全大對象,所以我在內存中進行所有比較,並嘗試添加或更新每個對象。我的實體具有數據庫給定的ID ID,並且我從保證CMC_Id是唯一的API中檢索。
初始插入正常工作。第二個「更新」中出現錯誤。我相信發生了什麼事是我在跟蹤多個實體修改的每一個都具有0
一個id,我試圖按照這樣的:https://msdn.microsoft.com/en-us/library/jj592676(v=vs.113).aspx
和錯誤我得到的是:"The instance of entity type 'Currency' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context."
我我不確定如何繼續更新每一行。
我已經通過簡單的刪除所有的硬幣,然後重新添加,標誌着當種子編號過高而將其復位bandaided這個問題。該過程大約需要7秒。 –