英文:
Is there CurrentValues.SetValues equivalent on SQLite?
问题
在我的Xamarin Forms中遇到了一个问题,我只想使用模型类来更新特定字段。
await validateToken.Update(new Auth
{
pid = defaultUser.pid,
defaultUser = "N"
});
但是当我使用上面的代码进行更新时,它会将所有未声明的字段置为null。在EF中,我只是使用_context.Attach(exist).CurrentValues.SetValues(UpdatedObj)
,我对SQLite不太确定。或者我可以在传递给Update时删除所有空属性吗?
英文:
Having problem on my Xamarin forms where I want to update specific fields only using model class.
await validateToken.Update(new Auth
{
pid = defaultUser.pid,
defaultUser = "N"
});
public async Task<int> Update(T entity) {
return await db.UpdateAsync(entity);
}
But when I update using above code, it nulls all the fields that are not declared. In EF I just used _context.Attach(exist).CurrentValues.SetValues(UpdatedObj)
I'm not very sure on SQLite. Or can I just removed all the null properties when passing to Update?
答案1
得分: 0
感谢Jason的评论。我得出了一个想法,您需要获取整个旧对象并将其与新对象进行比较,然后放入新值。以下是我的解决方案。
public async Task<int> Update(Auth entity)
{
Auth exist = await Get(entity.pid);
var updateObj = (Auth)CheckUpdateObject(exist, entity);
return await booking.Update(updateObj);
}
public static object CheckUpdateObject(object originalObj, object updateObj)
{
foreach (var property in updateObj.GetType().GetProperties())
{
if (property.GetValue(updateObj, null) == null)
{
property.SetValue(updateObj, originalObj.GetType().GetProperty(property.Name)
.GetValue(originalObj, null));
}
}
return updateObj;
}
希望对您有所帮助。
英文:
Thanks to Jason's comment. I came out to that idea where you need to get the whole old object and compare to the new object and put the new value. Below is my solution on my question.
public async Task<int> Update(Auth entity)
{
Auth exist = await Get(entity.pid);
var updateObj = (Auth)CheckUpdateObject(exist, entity);
return await booking.Update(updateObj);
}
public static object CheckUpdateObject(object originalObj, object updateObj)
{
foreach (var property in updateObj.GetType().GetProperties())
{
if (property.GetValue(updateObj, null) == null)
{
property.SetValue(updateObj, originalObj.GetType().GetProperty(property.Name)
.GetValue(originalObj, null));
}
}
return updateObj;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论