【问题标题】:Map a NULL value from database to Property of object将 NULL 值从数据库映射到对象的属性
【发布时间】:2019-05-14 19:39:52
【问题描述】:

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

C# 中具有 Nullable 值的对应 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 获取我的表的 ligns。

当我执行查询时出现错误:

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 中?

【问题讨论】:

  • 你有没有考虑过使用 ORM 代替?
  • 现在我做不到,我在一个需要深度重构的旧应用程序上(没有服务或 ORM)。但我发现错误是对字节的小整数,而不是我的对象中的整数。

标签: c# sql-server mapping


【解决方案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; }
}

【讨论】:

    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    相关资源
    最近更新 更多