C# Entityframework - How to clear FK field?

Asked

Viewed 25 times

0

I need help with an entity update operation by Entityframework

I want to clear a relationship between two entities. Imagine an example scenario below, I have an "Agent" entity for general use, and an entity settings for salary-related agents:

    public class Agente
    {

        public int Id { get; set; }
        public string Nome { get; set; }
    }

    public class ConfigSalario
    {
        public int Id { get; set; }
        public Agente AgenteSalario { get; set; }
        public Agente AgenteAdiantamento { get; set; }
        public Agente AgenteFerias { get; set; }
        public Agente Agente13 { get; set; }
    }

When I perform an update on the Configsalario entity, changing some of the agents indicating the new agent’s id, the update works correctly and the change is done in bank, through the code below:

configSalario.AgenteSalario = contexto.Agentes.Find(novoAgenteId);
contexto.ConfigSalario.Update(configSalario);
contexto.SaveChanges();

The problem occurs when I send one of the agents as null, in order to delete the specific agent within the settings table.

configSalario.AgenteSalario = null;
contexto.ConfigSalario.Update(configSalario);
contexto.SaveChanges();

The result.... occurs nothing, entityframework does not erase the value in the above situation. How do I delete the value of a table field in EF, especially if this field is a table FK, and my only goal is to undo the link????

EDIT. In the salary settings table in the bank allows null in the agent fields. Sqlserver usage.

1 answer

0

Even if you allow null in the Fk property in the table, you have to inform the Ef core.

public Guid? AgenteSalarioId {get: set:}

This way Ef core will understand that it is possible to receive null in the property AgenteSalario

I hope I helped, good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.