实体框架核心忽略null更新

时间:2019-08-17 22:04:32

标签: .net-core entity-framework-core ef-core-2.1

我的EF模型如下:

public class Base
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

public class Foo : Base
{
    public IEnumerable<Bar> Bars { get; set; }
}

public class Bar : Base
{
    ...
}

我的意图是以这样一种方式构建API:如果在更新中指定null,它将丢弃该值,但似乎无法正常工作。在我的存储库更新代码中,执行以下操作:

public override IEnumerable<Base> Update(IEnumerable<Base> items)
{
    foreach (var item in items.OfType<Foo>())
    {
        var existingItem = _context.Foos.Find(item.Id);
        if (existingItem == null)
        {
            throw new InvalidOperationException(
                $"Can't update item of type `{typeof(Foo)}` as it doesn't exist. ");
        }

        var entry = _context.Entry(existingItem);
        entry.CurrentValues.SetValues(item);

        foreach (var property in entry.Properties)
        {
            var original = property.OriginalValue;
            var current = property.CurrentValue;
            property.IsModified = original != null && !original.Equals(current);
        }

        var collection = entry.Collection(nameof(Foo.Bars));
        if (collection.CurrentValue == null)
            collection.IsModified = false;
    }

    var rows = _context.SaveChanges();
    return Read(items.Select(e => e.Id));
}

由于Foo.Bars属性实际上是一个Collection / Navigation属性,因此没有OriginalValue属性,只有CurrentValue,这意味着如果它为null,则不能丢弃该值。同样,将collection.IsModified设置为false似乎无效,并且无论Foo.Bars状态如何,IsModified属性都设置为null。

正在寻求有关处理此问题或我所缺少的更好方法的建议。谢谢。

0 个答案:

没有答案