【问题标题】:The specified cast from a materialized 'System.Int32' type to the 'System.Int64' type is not valid从具体化的“System.Int32”类型到“System.Int64”类型的指定转换无效
【发布时间】:2017-01-17 09:15:18
【问题描述】:

在执行以下查询时,我收到错误:-

public MioLMOrderConfirmAddress GetAddress(long headerId,int addressCategory)
    {
        using (var c = new TenantEntities(_tenantConString))
        {
            var data =
                c.MioLMOrderConfirmAddresses.FirstOrDefault(
                    x => x.MioLMOrderConfirmHeaderId == headerId && x.AddressCategoryId == addressCategory);
            return data;
        }
    }

错误:

附加信息:具体化的指定演员表 'System.Int32' 类型到 'System.Int64' 类型无效。

我的模型课在这里

public partial class MioLMOrderConfirmAddress
{
    public long Id { get; set; }
    public long MioLMOrderConfirmHeaderId { get; set; }
    public Nullable<long> MioLMOrderConfirmLineId { get; set; }
    public int AddressCategoryId { get; set; }
    public string FullAddress { get; set; }
    public string StreetName { get; set; }
    public string AdditionalStreetName { get; set; }
    public string CityName { get; set; }
    public string PostalZone { get; set; }
    public string CountrySubEntity { get; set; }
    public string CountryCode { get; set; }
    public string BuildingNumber { get; set; }
    public string AddressFormatCode { get; set; }
    public string AddressTypeCode { get; set; }
    public string BlockName { get; set; }
    public string BuildingName { get; set; }
    public string CitySubDivisionName { get; set; }
}

如何解决这个错误?

这是 MioLMOrderConfirmAddress 表的截图 MioLMOrderConfirmAddress Table

【问题讨论】:

  • 尝试x =&gt; x.MioLMOrderConfirmHeaderId == Convert.ToInt64(headerId)或将headerId参数重新声明为long
  • 在数据库中是MioLMOrderConfirmHeaderId int 还是AddressCategoryIdbigint
  • @Tim 'MioLMOrderConfirmHeaderId 是 'bigint' 而 'AddressCategoryId ' 是 'int'
  • 可能由于其他任何属性而引发异常。请发布表架构和 full 异常,包括其调用堆栈。这将显示异常实际发生的位置。您可以使用Exception.ToString() 获得完整的例外情况。至少发布数字属性的数据库类型 - 其中一个可能不是bigint,或者它是返回int的某个表达式的结果

标签: c# asp.net-mvc entity-framework linq


【解决方案1】:

代码优先用户的答案...

如果您可以将值保存在“int”中,则可以通过将属性从 long 转换为 int(以及从 long? 转换为 int?)来解决此问题。

然后,在 OnModelCreating 方法中告诉您的字段实际上是“bigint”或“decimal”:

modelBuilder
    .Properties()
    .Where(p => p.Name.EndsWith("Id"))
    .Configure(c => c.HasColumnType("bigint"));

如果您的数据库列是 int、bigint 或 decimal,则此方法有效。

希望这可以帮助其他人解决这个问题

【讨论】:

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