实体框架核心错误事务 20205

时间:2021-04-05 19:42:39

标签: c# entity-framework-core .net-5

我在 .NET5 Web 项目中遇到了 Entity Framework Core 5.0.4 的问题。

我有一个 BaseRepository<T>,我在其中定义了所有函数,例如(完整实现 here

public class BaseRepository<T> : IAsyncRepository<T> where T : class
{
    /// <summary>
    /// The log
    /// </summary>
    protected readonly ILogger _log;

    /// <summary>
    /// The database
    /// </summary>
    protected PSCContext _db;

    public BaseRepository(PSCContext db, ILogger<BaseRepository<T>> log)
    {
        _db = db;
        _log = log;
    }

    /// <summary>
    /// Add a new entity as an asynchronous operation.
    /// </summary>
    /// <param name="entity">The entity.</param>
    /// <returns>A Task&lt;T&gt; representing the asynchronous operation.</returns>
    public async Task<T> AddAsync(T entity)
    {
        _log.LogDebug($"[{nameof(T)}] Adding a new record");

        await _db.Set<T>().AddAsync(entity);
        await _db.SaveChangesAsync();

        return entity;
    }
}

我项目中的所有存储库都基于这个基类。我的程序中有很多插入。当我必须使用 enum 在存储库中保存新记录时,出现以下错误:

<块引用>

失败:Microsoft.EntityFrameworkCore.Database.Transaction[20205] 使用事务时出错。

你在下图中怎么看,我在这个错误之前有很多插入。在我的代码中根本没有交易。当我想保存时发生错误

enter image description here

表的定义是

[Table("ImportedHistoryFileLogs")]
public class ImportedHistoryFiletLog : ITable
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long ID { get; set; }
    public DateTime CreatedAt { get; set; } = DateTime.Now;
    public string CreatedBy { get; set; }
    public DateTime? ModifiedAt { get; set; }
    public string ModifiedBy { get; set; }
    public long ImportedHistoryFileId { get; set; }
    [ForeignKey("ImportedHistoryFileId")]
    public ImportedHistoryFile ImportedHistoryFile { get; set; }
    public DateTime LogData { get; set; } = DateTime.Now;
    public LogType LogType { get; set; } = LogType.Information;
    public LogEventType LogEventType { get; set; } = LogEventType.InternalAction;
    public string Body { get; set; }
    public string Message { get; set; }
    public string UserId { get; set; }
}

此表与另一个表 ImportedHistoryFile 有关系。在错误之前,我在此表中为其他记录添加了相同的代码。

并不总是有这个错误。有时程序会停止而没有任何错误或消息。

另外,我注意到在其他表中也有同样的错误。然后,我认为 Entity Framework Core 有许多操作(如缓冲区或并发),当我达到操作的最大值时,它会给我一个错误。我怎样才能避免这个错误?

更新

问题是否与SaveChangesAsync()有关?显然,如果我用 _db.SaveChanges(); 更改该行是有效的。

0 个答案:

没有答案