Gonzalo
Gonzalo

Reputation: 2876

Delete foreign key when related entity is set to null on attached entity

I have a DAO class that update an entity received from a client app. So I attach the entity to the context, but if a related entity is set to null in the client, after save the foreingn key is not set to null in the database,and then when I query entity, the related entity still there.

How I can delete foreing key in this case? (I can't examine each property manually, because the model is to big)

EDIT: It works fine when I query de entity in the dbcontext, the problem is when the entity is modified in the client and then attached to the dbcontext.

This is an example: when I set person.Address.Neighborhood = null; the NeighborhoodId property still 7 in the int the Address table.

var person = new Person
{
    Id = 1,
    Name = "Juan",
    Adress = new Address
    {
        Id = 3,
        StreetName = "Calle Falsa",
        StreetNumber = "123",
        Neighborhood = new Neighborhood
        {
            Id = 7,
            Description = "my Neighborhood"
        },
    }
};

person.Address.Neighborhood = null; 

_context.Attach(person);
_context.Entry(person).State = EntityState.Modified;
var unchange = _context.ChangeTracker.Entries().Where(e => e.State == EntityState.Unchanged).ToList();
if (unchange != null && unchange.Count > 0)
{
    foreach (var unaEntidad in unchange )
    {
        _context.Entry(unaEntidad.Entity).State = EntityState.Modified;
    }
}

_context.SaveChanges();

EDIT: The classes:

public class Person
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Address Address { get; set; }
}

public class Address
{
    public virtual int Id { get; set; }
    public virtual string StreetName { get; set; }
    public virtual string StreetNumber { get; set; }
    public virtual Neighborhood Neighborhood { get; set; }
}

public class Neighborhood
{
    public virtual int Id { get; set; }
    public virtual string Description { get; set; }
}

Upvotes: 1

Views: 456

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205529

The problem is (could be a bug?) that .State = EntityState.Modified; does not mark the null reference navigation properties as modified (which otherwise it does for primitive and non null reference navigation properties).

The fix/workaround is to manually mark them as modified after setting the entity state with code like this:

foreach (var reference in _context.Entry(person).References)
    reference.IsModified = true;

Upvotes: 1

aqteifan
aqteifan

Reputation: 504

Person model should have a nullable address entity

public class Person {
  public Nullable<Address> Adress {get;set;}
}

Upvotes: 0

Related Questions