我正在使用EF/自动映射。外键出错。使用try...catch,我想捕获错误。我想更进一步,插入/更新数据。
但我的想法是,这个过程仍然处于相同的异常中。它看起来和LINQ-to-SQL一样。SaveChanges-方法尝试保存在堆栈中等待保存的所有更新。
是否可以清除保存进程?
LogMessagesService中的插入方法
public int Insert(LogBerichtDto LogBerichtDto)
{
LogBericht entity = _mapper.Map<LogBerichtDto, LogBericht>(LogBerichtDto);
_logBerichtRepository.Insert(entity);
_logBerichtRepository.Save();
return entity.Id;
}在GenericRepository中
public void Save()
{
_context.SaveChanges();
}

发布于 2021-07-25 05:02:16
当我有时间处理自己的应用程序时,我可以找出问题出在哪里?有几个问题。但我认为未保存的更改主要存在于缓存中。
格特·阿诺德的话就是我解决这个问题的方法。
这是我的GenericRepository代码。不再是上下文的注入。并在需要时创建新的。你可以开枪。但是导入过程不再挂起。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace MyData.Repository
{
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private MyDbContext _context;
private DbSet<T> table = null;
public GenericRepository()
{
_context = GetNew();
}
public DbContext Current
{
get { return _context; }
}
public virtual void Reset()
{
_context.Dispose();
_context = GetNew();
}
public MyDbContext GetNew()
{
MyDbContext context = new MyDbContext();
table = context.Set<T>();
return context;
}
public IQueryable<T> Where(Expression<Func<T, bool>> filter)
{
return table.Where(filter);
}
public IEnumerable<T> GetAll()
{
return table.ToList();
}
public async Task<T> GetById(object id)
{
return await table.FindAsync(id);
}
public async Task Insert(T obj)
{
await table.AddAsync(obj);
}
public async Task Update(int id, T obj)
{
var entry = await table.FindAsync(id);
_context.Entry(entry).CurrentValues.SetValues(obj);
}
public async Task Delete(int id)
{
T existing = await table.FindAsync(id);
table.Remove(existing);
}
public async Task Save()
{
try
{
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
Reset();
throw;
}
_context.ChangeTracker.Clear();
}
}
}https://stackoverflow.com/questions/67297916
复制相似问题