Using QueryByAttribute cannot retrieve null values

Deadly 提交于 2019-12-01 06:21:36
Konrad Viltersten

The error occurs because a field with no entered value won't get returned in the context object not the image. Or to put it graspably - you need to check whether a field is amongst the attributes.

It's not sufficient to have declared it and requested it via ColumnSet. It's confusing and annoying (been there myself).

Just of the top of my head, I can think of the following code snippet to manage the issue (without having to set an if clause for every read but also avoiding a bunch of methods - one for each variable type).

private Generic GetEntityValue<Generic>(
  Entity entity, String field, Generic substitute = default(Generic))
{
  if (entity.Contains(field))
    return (Generic)entity[field];
  return substitute;
}

edit: Or as an extension method

public static T GetAttributeValue<T> (this Entity e, string propertyName, T defaultValue = default(T))
{
    if (e.Contains(propertyName))
    {
        return (T)e[propertyName];
    }
    else
    {
        return defaultValue;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!