哪種方式更加正確的刪除實體?連接到SQL Server進行事務的方式是正確的
正確的方法:對於很多行,我們應該使用方式,是工作結束後,更多的信任,能和關閉交易
首先嘗試:
public class UserRepository : IDisposable
{
private DomainModels.BotEntities _dbDnt = null;
public UserRepository()
{
_dbDnt = new DomainModels.IraniBotEntities();
}
public bool Delete(int id, bool autoSave = true)
{
try
{
var entity = _dbDnt.Users.Find(id);
_dbDnt.Entry(entity).State = EntityState.Deleted;
if (autoSave)
return Convert.ToBoolean(_dbDnt.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
public int Save()
{
try
{
return _dbDnt.SaveChanges();
}
catch
{
return -1;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this._dbDnt != null)
{
this._dbDnt.Dispose();
this._dbDnt = null;
}
}
}
~UserRepository()
{
Dispose(false);
}
}
,然後用像這樣的:
UserRepository repA = new UserRepository();
repA.Delete(user);
二嘗試:
using (var dbContext = new IraniBotEntities())
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
哪種方式更正確?因爲我用第一種方式使用hangfire,而我的服務器上的cpu會100%
二。只要一個工作單元停機,您應該始終處理數據庫資源。據說這可能不是你的CPU「達到100%」的原因。 – juharr
那我該怎麼辦? –
這兩種方式都不會讓你的CPU變得很高。這裏還有其他的錯誤。你發佈的任何一種方法都應該沒問題。您需要對您的應用程序進行配置,以瞭解發生了什麼。第一種方法的優點是可以在調用SaveChanges之前執行多個操作,因此您可以跨多個語句執行單個事務。所以不要聽那些說第二種方法總是最好的。 – mason