gpt4 book ai didi

c# - 无法转换 EntityEntry 当前值

转载 作者:行者123 更新时间:2023-11-30 23:13:51 24 4
gpt4 key购买 nike

我在 EF 6 中有相同的方法并且工作得很好,但是使用 EF core v1.1.1 是方法抛出这样的异常。请看一下。 enter image description here

     public virtual T Update(T obj)
{
try
{
if (null == obj) throw new ArgumentNullException(nameof(obj));

_context.Set<T>().Attach(obj);

var entry = _context.Entry(obj);

foreach (var property in entry.OriginalValues.Properties)
{
var current = entry.CurrentValues.GetValue<object>(property.Name); // <-- error occurring this line. If i set the generic type to specific like int,string etc the code work for the specific type only but if i set to object won't work.
entry.Property(property.Name).IsModified = current != null;
}

_context.SaveChanges();

//Detached the current context to get changes value
_context.Entry(obj).State = EntityState.Detached;

return obj;
}
catch (Exception ex)
{

Console.Write(ex);
throw;
}
}

最佳答案

使用索引器无需强制转换即可获取属性值:

var current = entry.CurrentValues[property.Name];

主键属性应该从 foreach 循环中排除。像这样的东西:

if (property.Name == "Id") continue;

应该可以。否则你会得到InvalidOperationException:

'The property 'Id' on entity type 'Foo' is part of a key and so cannot be modified or marked as modified.'

关于c# - 无法转换 EntityEntry 当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43426882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com