繁体   English   中英

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

[英]Map a NULL value from database to Property of object

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

在此处输入图片说明

具有Nullable值的C#中对应的DataObject(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)是Byte而不是integer? 如何将NUll映射到相应的属性(BurstPlateformTypeId)Null?

经过进一步调查:

SQL中的tinyInt被认为是C#中的字节,因此我的dataobject是false。

我的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; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM