I'm having a problem, in fact it should be the lack of knowledge even at the time of deleting a record using Entity Framework 6.
When I try to delete a record that can not be deleted because it has references, it gives the following error:
Sofar,allright.
I'lltrytodeleteanotherrecord,whichI'msurehasnoreference,anditgivesthesameerror,it'sactuallytryingtodeletethepreviousrecordagain.
IfIleavethescreenandenteragainthenIcandeletetheregistrynormally,aslongasIdonottrytodeleteanotheronebeforeitgeneratestheerror.
Doesanyonehavealight?Vlw
EDIT:Here'smycodetobetterunderstand:
ScreenSignature:
privatereadonlyICategoriaAppService_categoriaApp;privateCategoriaViewModel_categoria;publicFormCategorias(ICategoriaAppServicecategoriaAppService){_categoriaApp=categoriaAppService;InitializeComponent();}
Methodtoexclude:
privatevoidbtnExcluir_Click(objectsender,EventArgse){DialogResultresposta=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: Resolved by putting try catch and remapping Db.Context. Code changed above.