将NULL值从数据库映射到对象的属性

时间:2018-12-13 14:44:51

标签: c# sql-server mapping

我在SQL Server中有一个表,其中某些列(tinyint)的值为Null,如下所示:

enter image description here

C#中具有Nullable值的相应数据对象(tbh_id上的burstHierarchyTypeId映射和tbp_id上的burstPlateformTypeId映射):

public class BurstShortCutDo : BaseDomain
{

private long _adfId = ValueTypeUtils.Instance.LongNull;
private string _websitesIds;
private string _shortCutValue = "";
private int? _burstHierarchyTypeId = null;
private int? _burstPlateformTypeId = null;


#region CONSTRUCTORS

public BurstShortCutDo()
{
}
#endregion

#region PROPERTIES
public long AdfId
{
    get { return _adfId; }

    set { _adfId = value; }
}

public int? BurstHierarchyTypeId
{
    get { return _burstHierarchyTypeId; }
    set { _burstHierarchyTypeId = value; }
}

public int? BurstPlateformTypeId
{
    get { return _burstPlateformTypeId; }
    set { _burstPlateformTypeId = value; }
}

public string ShortCutValue
{
    get { return _shortCutValue; }
    set { _shortCutValue = value; }
}
}

我有一个查询,可根据ComId获取表的木质素。

执行查询时出现错误:

Invalid cast from 'System.Byte' to 'System.Nullable`1

这是Setter(来自PropertyUtils.cs):

private void SetPropertySimpleName(object obj, string propName, object propValue)
{
PropertyInfo propInfo = obj.GetType().GetProperty(propName);
if (propInfo != null && propInfo.CanWrite)
{
    if (propValue == null && !propInfo.PropertyType.IsValueType)
    {
        propInfo.SetValue(obj, null, null);
    }
    else if (propInfo.PropertyType.IsAssignableFrom(propValue.GetType()))
    {
        propInfo.SetValue(obj, propValue, null);
    }
    else if (propValue is IConvertible)
    {
        // CRASH HERE 
        propInfo.SetValue(obj, Convert.ChangeType(propValue, propInfo.PropertyType, CultureInfo.CurrentCulture), null);
    }
}
else 
{
    throw new ObjectNotFoundException("The property '" + propName + "' is not found in class '" + obj.GetType().FullName + "'");
}
}

尝试设置BurstPlateformTypeId(tbp_id = 1)的值时出现错误消息:

  Invalid cast from 'System.Byte' to 'System.Nullable`1

Convert.ChangeTpe来自C#的元数据,据我了解,查询获得的值是“ 1”,因此它检测到整数,但是当它从对象检查属性的类型时,它将得到可为空的值

为什么我的属性值(1)是字节型而不是整数型? 如何将NUll映射到相应的属性(BurstPlateformTypeId)Null中?

1 个答案:

答案 0 :(得分:1)

进一步调查后:

SQL中的tinyInt被认为是C#中的字节,因此我的数据对象为假。

我的dataobject中的解决方案:

private byte? _burstHierarchyTypeId = null;
private byte? _burstPlateformTypeId = null;

public byte? BurstHierarchyTypeId
{
   get { return _burstHierarchyTypeId; }
   set { _burstHierarchyTypeId = value; }
}

public byte? BurstPlateformTypeId
{
   get { return _burstPlateformTypeId; }
   set { _burstPlateformTypeId = value; }
}