我在azure上託管一個.Net Web Api,這個API只是更新了一個sql server數據庫中的一行。這裏是我的UPDATECODE:Azure Entityframework SaveChanges非常慢
using (Storage ctx = new Storage())
{
string json = JsonConvert.SerializeObject(ev, _jsonsettings);
Data ex = ctx.dbsData.FirstOrDefault();
if (ex == null)
ctx.dbsData.Add(new Data() { Json = json, LastUpdate = DateTime.Now });
else
{
ex.Json = json;
ex.LastUpdate = DateTime.Now;
ctx.Entry(ex).State = EntityState.Modified;
}
ctx.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
和我有,僅清除表中的第二種方法:
[HttpDelete]
public HttpResponseMessage Clear()
{
using (Storage ctx = new Storage())
{
ctx.dbsData.RemoveRange(ctx.dbsData);
ctx.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
參見我的DbContext類:
public class Storage : DbContext
{
public DbSet<Data> dbsData { get; set; }
public Storage(string connectionstring) : base(connectionstring)
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
Configuration.ValidateOnSaveEnabled = false;
Configuration.AutoDetectChangesEnabled = false;
}
public Storage() : this("tom")
{
}
}
我的問題是,這兩個方法極其緩慢。我發現如果我刪除SaveChanges()命令,它會以更快的速度執行。所以我的問題是我如何提高性能,爲什麼需要很長時間來更新/刪除單行?
刪除SaveChanges()時速度更快的原因是因爲沒有它,數據庫不會更新。 SaveChanges()是查詢在數據庫中實際執行的點。對於一行,它不應該慢。然而,需要更多的信息,你存儲在其中一列中的json數據有多大?它最終會保存還是隻是超時? – MartinM
我知道savechanges()更新數據庫。我不明白的是爲什麼它很慢(約10秒)。我的json的大小約爲500kb。如果我在我的sqlexpress服務器本地嘗試它,立即存儲,不會有任何延遲。 –
您能否提供有關您使用Azure的更多信息?它是具有Azure SQL數據庫的VM或App Service嗎?當你在本地嘗試時,你的意思是你將你的Azure WebApi connectionstring設置爲你本地的sqlexpress?您是否嘗試過將本地連接字符串設置爲Azure SQL數據庫? –