首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以清除保存进程(EF/AutoMappIng)?

是否可以清除保存进程(EF/AutoMappIng)?
EN

Stack Overflow用户
提问于 2021-04-28 17:54:36
回答 1查看 35关注 0票数 0

我正在使用EF/自动映射。外键出错。使用try...catch,我想捕获错误。我想更进一步,插入/更新数据。

但我的想法是,这个过程仍然处于相同的异常中。它看起来和LINQ-to-SQL一样。SaveChanges-方法尝试保存在堆栈中等待保存的所有更新。

是否可以清除保存进程?

LogMessagesService中的插入方法

代码语言:javascript
复制
public int Insert(LogBerichtDto LogBerichtDto)
{
    LogBericht entity = _mapper.Map<LogBerichtDto, LogBericht>(LogBerichtDto);

    _logBerichtRepository.Insert(entity);
    _logBerichtRepository.Save();

    return entity.Id;
}

在GenericRepository中

代码语言:javascript
复制
public void Save()
{
    _context.SaveChanges();
}

EN

回答 1

Stack Overflow用户

发布于 2021-07-25 05:02:16

当我有时间处理自己的应用程序时,我可以找出问题出在哪里?有几个问题。但我认为未保存的更改主要存在于缓存中。

格特·阿诺德的话就是我解决这个问题的方法。

这是我的GenericRepository代码。不再是上下文的注入。并在需要时创建新的。你可以开枪。但是导入过程不再挂起。

代码语言:javascript
复制
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();
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67297916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档