My project's MVC is built into services, controllers, Views, and models.
My delete screen works, but when the log is used in other tables it displays this error.
The DELETE statement conflicted with the REFERENCE constraint "FK_XYZ". The conflict occurred in database "ETEST", table "dbo.TEST", column 'ID_TEST'.
The statement has been terminated.
This happens because the table's PK is FK in other tables.
I would like before deleting, the system would check if the registry is used in the database. To display a message to the friendly user before attempting to delete. Eg: Record can not be deleted because it is in use.
How do I construct this validation?
Model
public int Id {get; set;}
[Display(Name = "Codigo", ResourceType = typeof(Resources.TestResources))]
[Required]
public string Codigo { get; set; }
[Display(Name = "Descricao", ResourceType = typeof(Resources.TestResources))]
[Required]
public string Descricao { get; set; }
[Display(Name = "UsuarioAnalistaCusto", ResourceType = typeof(Resources.TestResources))]
[Required]
public string UsuarioAnalistaCusto { get; set; }
Controller
public void Excluir(int id)
{
this.Service.Delete(id);
}
Services
public void Delete(int id)
{
var item = this.context.Test.Find(id);
this.context.Test.Remove(item);
base.Save();
}
Context
namespace TXT.Test.eTest.DataAccess
{
public partial class EContext : DbContext
{
static EContext()
{
Database.SetInitializer<ECContext>(null);
}
public EContext(bool proxyCreationEnabled = true)
: base("Name=EContext")
{
base.Database.CommandTimeout = 60 * 5; // TOOO: utilizar configuration
base.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
base.Configuration.AutoDetectChangesEnabled = false;
}
public DbSet<Empresa> Empresas { get; set; }
public DbSet<Fornecedor> Fornecedores { get; set; }
public DbSet<Desenho> Desenhos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new EMPRESAMap());
modelBuilder.Configurations.Add(new FORNECEDORMap());
modelBuilder.Configurations.Add(new DESENHOMap());
...
}
...
}
}