标签:detail logs enum string led ddr null text ESS
相关资源:https://www.cnblogs.com/Laimic/p/9172844.html(EntityFrameworkCore - 内存数据库)
在使用EF框架时,我们通常都是通过调用SaveChanges方法把增加/修改/删除的数据提交到数据库,但是上下文是如何知道实体对象是增加、修改还是删除呢?答案是通过EntityState的枚举值来判断的。也就是说在操作数据库时,EF会根据EntityState这个枚举检测到实体的状态,然后执行相应的增/删/改操作。
该状态对应的值为以下五种:
Detached:对象存在,但未由对象服务跟踪。在创建实体之后、但将其添加到对象上下文之前,该实体处于此状态;
Unchanged:自对象加载到上下文中后,或自上次调用 System.Data.Objects.ObjectContext.SaveChanges() 方法后,此对象尚未经过修改;
Added:对象已添加到对象上下文,但尚未调用 System.Data.Objects.ObjectContext.SaveChanges() 方法;
Deleted:使用 System.Data.Objects.ObjectContext.DeleteObject(System.Object) 方法从对象上下文中删除了对象;
Modified:对象已更改,但尚未调用 System.Data.Objects.ObjectContext.SaveChanges() 方法。
public virtual void Insert(IEnumerable<TEntity> entities) { if (entities == null) throw new ArgumentNullException(nameof(entities)); try { Entities.AddRange(entities); _context.SaveChanges(); } catch (DbUpdateException exception) { //ensure that the detailed error text is saved in the Log throw new Exception(GetFullErrorTextAndRollbackEntityChanges(exception), exception); } }
/// <summary> /// 回滚实体更改并返回完整的错误消息 /// </summary> /// <param name="exception">Exception</param> /// <returns>Error message</returns> protected string GetFullErrorTextAndRollbackEntityChanges(DbUpdateException exception) { //rollback entity changes if (_context is DbContext dbContext) { var entries = dbContext.ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.State == EntityState.Modified).ToList(); entries.ForEach(entry => { try { entry.State = EntityState.Unchanged; } catch (InvalidOperationException) { // ignored } }); } try { _context.SaveChanges(); return exception.ToString(); } catch (Exception ex) { //if after the rollback of changes the context is still not saving, //return the full text of the exception that occurred when saving return ex.ToString(); } }
通过add-migration InitialCreate命令
标签:detail logs enum string led ddr null text ESS
原文地址:https://www.cnblogs.com/gougou1981/p/12228714.html