[英]EF Repository with UoW Update
我相信这是在其他地方提出来的,但我找不到直接的解决方案。 我的Api正在传递对象模型,并且在服务器端,该未传递对象的每个值都被视为null(有意义)。 有没有办法我可以告诉EF6不要用传递的对象中的空值更新实体,而不必编写每个属性并检查它是否为空。
伪代码
API
Update(int id, TaskEntity obj)
{
unitOfWork.Tasks.Update(id, userTask);
...
unitOfWork.Save()
}
回购更新
Update(int id, T entity)
{
var existingRecord = Get(id); //Gets entity from db based on passed id
if (existingRecord != null)
{
var attachedEntry = Context.Entry(existingRecord);
attachedEntry.CurrentValues.SetValues(entity);
}
}
我的问题是,具有空值的任何数据实际上都会重写具有空值的现有数据库记录值。
请指出解决方案或文章。 我应该反思一下,也许自动映射器可以解决这个问题(我相信这不是它的目的),或者应该编写某种辅助方法,因为我的对象可以包含子对象。
先感谢您。
你可以做这样的事情
Update(int id, T entity,string[] excludedFields)
{
var existingRecord = Get(id); //Gets entity from db based on passed id
if (existingRecord != null)
{
var attachedEntry = Context.Entry(existingRecord);
attachedEntry.CurrentValues.SetValues(entity);
for(var field in excludedFields)
{
attachedEntry.Property(field).IsModified = false;
}
}
}
有些场景需要您更新对象的一部分,有时需要更新其他部分,我认为最好的方法是传递字段以将其排除在更新之外
希望对你有帮助
就个人而言,不喜欢在更新之前先打数据库并执行get操作。 可能在进行ajax调用时,您可以发送应更新的属性列表(以便也可以处理更新为null值(擦除现有值)的情况)。
我正在对@Hadi Hassan所做的事情做一些小修改(无需访问数据库即可获取实体):
Update(T entity,string[] includedFields)
{
var existingRecord = Context.Attach(entity); // assuming primary key (id) will be there in this entity
var attachedEntry = Context.Entry(existingRecord);
for(var field in includedFields)
{
attachedEntry.Property(field).IsModified = true;
}
}
注意-AttachedEntry.Property(field).IsModified不适用于相关实体
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.