Error trying to save information to the database through the Entity Framework

0

My project has the following classes:

public class Manifestacao
{
    public long Id { get; set; }
    public string NumeroChamado { get; set; }
    public virtual Cliente Cliente { get; set; }

    public virtual List<Conteudo> Conteudos { get; set; }
}

public class Conteudo
{
    public long Id { get; set; }
    public string Categoria { get; set; }
    public string SubCategoria { get; set; }
    public string Descricao { get; set; }

    public string Status { get; set; }
    public string Obs { get; set; }
    public string Evidencias { get; set; }

    public long UsuarioAberturaId { get; set; }
    public virtual Usuario UsuarioAbertura { get; set; }

    public long UsuarioFechamentoId { get; set; }
    public virtual Usuario UsuarioFechamento { get; set; }

    public DateTime? DataHoraAbertura { get; set; }
    public DateTime? DataHoraFechamento { get; set; }

    public long ManifestacaoId { get; set; }
    public virtual Manifestacao Manifestacao { get; set; }
}

public class Usuario
{
    public long Id { get; set; }
    public string Apelido { get; set; }
    public string Nome { get; set; }
    public string Categoria { get; set; }
    public string Senha { get; set; }
    public string Status { get; set; }
}

The intent is to get the data entered into a form and save it to the database through the Entity Framework. Some form data is in textboxes and others in the datagridview. The user responsible for saving the information is also registered, so far so good. I instantiate the objects by taking the information from the form, according to the following code:

        var cliente = new Cliente
        {
            Empresa = txtEmpresaCliente.Text,
            Contato = txtContatoCliente.Text,
            Email = txtEmailCliente.Text,
            Telefone = mskTelefoneCliente.Text,
            Ramal = txtRamalCliente.Text,
            Celular = mskCelularCliente.Text
        };

        List<Conteudo> conteudosDgv = new List<Conteudo>();
        List<string> listaSubCategorias = new List<string>();            

        DateTime dataHoraAbertura = PegaDataHoraUsuario.DataHoraPadrao();

        foreach (DataGridViewRow row in dgvRegistros.Rows)
        {
            Conteudo conteudoLinha = new Conteudo();
            conteudoLinha.Categoria = (string)row.Cells["categoria"].Value;
            conteudoLinha.SubCategoria = (string)row.Cells["subcategoria"].Value;
            conteudoLinha.Descricao = (string)row.Cells["descricao"].Value;
            conteudoLinha.Status = "Novo";
            conteudoLinha.UsuarioAbertura = dalUsuario.GetUsuarioByID(UsuarioLogado.Id);
            conteudoLinha.DataHoraAbertura = dataHoraAbertura;
            conteudosDgv.Add(conteudoLinha);

            listaSubCategorias.Add(conteudoLinha.SubCategoria);
        }
        var manifestacao = new Manifestacao
        {
            Cliente = cliente,
            Conteudos = conteudosDgv,
            NumeroChamado = PegaDataHoraUsuario.nChamado(),
        };
        using (var context = new EFContext())
        {
            context.Manifestacoes.Add(manifestacao);
            context.SaveChanges();
            return true;
        }

When attempting to execute the excerpt that saves the data, the error is accused:

System.Data.SqlClient.SqlException: 'Introducing FOREIGN KEY constraint 'FK_dbo.Conteudoes_dbo.Usuarios_UsuarioFechamentoId' on table 'Conteudoes' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.'

I've added ForeignKey annotations to EF documentation > in the Content class:

    [ForeignKey("UsuarioAbertura")]
    public long UsuarioAberturaId { get; set; }
    public virtual Usuario UsuarioAbertura { get; set; }

    [ForeignKey("UsuarioFechamento")]
    public long UsuarioFechamentoId { get; set; }
    public virtual Usuario UsuarioFechamento { get; set; }

But still the same error persists.

    
asked by anonymous 04.10.2017 / 16:12

1 answer

1
 [ForeignKey("UsuarioAbertura")]
 public long UsuarioAberturaId { get; set; }
 public virtual Usuario UsuarioAbertura { get; set; }

Here you tried to map a ratio of 1 to 1? If you tried this incorrect, this is a fraction of the setting that makes the relationship from 1 to N, and this is enough for Entity to understand this relationship at the time of creating / editing the database.

I recommend: link

The problem is that the cascade delete is active. When you send Manifestation delete, it will delete deleting all related Contents and the same will delete deleting all Linked User, however I have 2 relationships for User, where both sides of the relationship can come off by dropping the same tables and this conflict will occur that the Entity Framework accused.

Manifestacao 
-->> DROP CASCADE Conteudo
     -->> DROP CASCADE Usuario (possui dois relacionamento "iguais" a sofrer exclusão)
          -->> UsuarioAbertura
          -->> UsuarioFechamento 

The solution is to sort this relationship if the intention is from 1 to 1 and if it is from 1 to N you will have to use the Fluent API to configure that it is not a cascade delete or use the following line to delete the convention of CASCADE DELETE no OnModelCreating() :

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    
04.10.2017 / 21:17