0
I’m having a problem, actually it must be the same lack of knowledge, at the time of deleting a record using Entity Framework 6.
When I try to delete a record that cannot be deleted because it has references, it gives the following error:
So far, so good.
Ai I will try to delete another record, which I am sure has no reference, and it gives the same error, in fact is trying to delete again the previous record.
If I exit the screen and enter again then I can delete the record normally as long as I don’t try to delete another one before it generates the error.
Does anyone have a light? VLW
EDIT: Follow my code to better understand:
Screen signature:
private readonly ICategoriaAppService _categoriaApp;
private CategoriaViewModel _categoria;
public FormCategorias(ICategoriaAppService categoriaAppService)
{
_categoriaApp = categoriaAppService;
InitializeComponent();
}
Method to exclude:
private void btnExcluir_Click(object sender, EventArgs e)
{
DialogResult resposta = MessageBox.Show("Deseja excluir este registro?", "Excluir", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
switch (resposta)
{
case DialogResult.Yes:
var categoriaDomain = _categoriaApp.ObtemPeloID(_categoria.Numero_Categoria);
_categoriaApp.Excluir(categoriaDomain);
MessageBox.Show("Registro excluido com sucesso");
break;
case DialogResult.No:
break;
}
}
Appservice:
private readonly ICategoriaService _categoriaService;
public CategoriaAppService(ICategoriaService categoriaService) : base(categoriaService)
{
_categoriaService = categoriaService;
}
public void Excluir(TEntity obj)
{
_serviceBase.Remove(obj);
}
Service:
public class ServiceBase<TEntity> : IDisposable, IServiceBase<TEntity> where TEntity : class
{
protected ControleEstoqueContexto Db = new ControleEstoqueContexto();
public ServiceBase()
{
Db.Configuration.AutoDetectChangesEnabled = false;
}
public virtual void Remove(TEntity obj)
{
try
{
Db.Set<TEntity>().Remove(obj);
Db.SaveChanges();
}
catch (Exception e)
{
Db.Dispose();
Db = new ControleEstoqueContexto();
throw e;
}
}
//ETC
}
EDIT 2: Solved by putting Try catch and redoing Db.Context. Above changed code.
You can put your code in the question?
– Leonel Sanches da Silva