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

问题描述 投票:0回答:1

我在SQL Server中的表列的一些(TINYINT),象这样的空值:

enter image description here

相应的数据对象在C#与空的值(上tbh_id和burstPlateformTypeId地图上tbp_id burstHierarchyTypeId地图):

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

这里是二传手(从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)考虑字节而不是整数?我怎样才能空映射到相应的属性(BurstPlateformTypeId)空?

c# sql-server mapping
1个回答
1
投票

进一步调查后:

在SQL TINYINT是考虑在C#中的字节,所以我的数据对象是假的。

在我的数据对象的解决方案:

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.