【问题标题】:System.InvalidOperationException: The specified cast from a materialized 'System.Int32' type to a nullable 'Country' type is not validSystem.InvalidOperationException:从具体化的“System.Int32”类型到可为空的“Country”类型的指定转换无效
【发布时间】:2013-03-06 01:06:45
【问题描述】:

我有一个在我的个人电脑上运行良好的特定单元测试,但是每当我让 TFS 运行测试时,它都会失败并出现以下异常 -

System.InvalidOperationException:从一个指定的转换 将 'System.Int32' 类型具体化为可为空的 'Country' 类型不是 有效。

通过跟踪堆栈跟踪,它与以下方法有问题 -

public IEnumerable<IAddress> AddressSelectAll(long userID)
{
    using (var context = new Entities())
    {
        var addresses = context.Customers
                               .Where(x => x.UserId == userID)
                               .Select(y => new Address
                                                {
                                                    Address1 = y.Address1,
                                                    Address2 = y.Address2,
                                                    Address3 = y.Address3,
                                                    AddressID = y.AddressId,
                                                    City = y.City,
                                                    Country = y.Country != null ? (Country)y.Country : (Country?)null,
                                                    Postcode = y.Postcode,
                                                    State = y.State,
                                                    RecordEntryDate = y.RecordEntryDate,
                                                    Type = (AddressType)EFFunctions.ConvertToInt32(y.AddressType),
                                                    UserID = y.UserId
                                                }).ToList();

        return addresses.ToList();
    }
}

如果它是相关的(怀疑是),我的 EFFunctions 类被定义为 -

public static class EFFunctions
{
    [EdmFunction("Model", "ConvertToInt32")]
    public static int ConvertToInt32(string text)
    {
        var result = string.IsNullOrEmpty(text) ? 0 : Convert.ToInt32(text);

        return result;
    }
}

我的 .edmx 包含以下内容 -

<Function Name="ConvertToInt32" ReturnType="Edm.Int32">
  <Parameter Name="v" Type="Edm.String" />
  <DefiningExpression>
    CAST(v AS Edm.Int32)
  </DefiningExpression>
</Function>

有人能告诉我我做错了什么吗?

【问题讨论】:

    标签: c# .net linq entity-framework


    【解决方案1】:

    您的问题可能与线路(或线路的一部分)有关

    Country = y.Country != null ? (Country)y.Country : (Country?)null
    

    您在一个案例中将值转换为 Country 和 Country?在另一个。也许您可以将值替换为 -1,或者更可靠地将 Customer.Country 类型更改为 Country?而不是国家/地区。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多