从实例化的 'System.Int32' 类型向 'System.Int64' 类型的指定转换无效。

5
在执行以下查询时,我收到了错误提示:-
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 表格


尝试使用 x => x.MioLMOrderConfirmHeaderId == Convert.ToInt64(headerId) 或重新声明 headerId 参数为 long - haim770
2
MioLMOrderConfirmHeaderId 在数据库中是 int 类型还是 AddressCategoryIdbigint 类型? - Tim Schmelter
可能重复问题:https://dev59.com/UFwY5IYBdhLWcg3wup9c - GDS
我认为问题出在你的模型数据类型上,MioLMOrderConfirmLineId 应该是 Nullable<int>。当然,如果数据库类型是 int 的话。 - M. Wiśnicki
1
异常可能由其他属性中的任何一个引发。请发布表模式和完整异常,包括其调用堆栈。这将显示异常实际发生的位置。您可以使用Exception.ToString()获取完整的异常。至少发布数值属性的数据库类型 - 其中一个可能不是bigint,或者它是返回int的某个表达式的结果。 - Panagiotis Kanavos
显示剩余2条评论
1个回答

0

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

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

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

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

如果您的数据库列是 int、bigint 或 decimal 类型,则此方法适用。

希望这能帮到其他遇到此问题的人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接