当关联实体在关联实体上设置为null时,删除外键

时间:2018-12-03 03:07:30

标签: c# entity-framework ef-core-2.0 ef-core-2.1

我有一个DAO类,用于更新从客户端应用程序接收到的实体。因此,我将实体附加到上下文,但是如果在客户端中将相关实体设置为null,则在保存数据库之后,将foreingn键保存为空后,再查询实体时,相关实体仍然存在。 / p>

在这种情况下如何删除前键? (我无法手动检查每个属性,因为模型很大)

编辑:当我在dbcontext中查询实体时,它工作正常,问题是当在客户端中修改实体然后将其附加到dbcontext时。

这是一个示例:当我在{strong>地址表的int中设置person.Address.Neighborhood = null; NeighborhoodId 属性仍然7 时。< / p>

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();

编辑:类:

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; }
}

2 个答案:

答案 0 :(得分:1)

问题是(可能是错误?),.State = EntityState.Modified;没有将null参考导航属性标记为已修改(否则,它会标记为原始和非null的参考导航属性)。

修复/解决方法是在使用以下代码设置实体状态后,将它们手动标记为已修改:

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

答案 1 :(得分:0)

人员模型应具有可为空的地址实体

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