【问题标题】:Entity Framework Core DbContext.SaveChanges throws System.InvalidCastException: Unable to cast object of type System.Boolean to type System.Int16实体框架核心 DbContext.SaveChanges 引发 System.InvalidCastException:无法将 System.Boolean 类型的对象转换为 System.Int16 类型
【发布时间】:2019-10-18 20:28:36
【问题描述】:

我正在使用 .net core 2.2 和使用 MySql.Data.EntityFramework.Core 的实体框架。当我执行以下操作时遇到此异常:

DbContext.MyDbSet.Add(new MyClass());
DbContext.SaveChanges();

例外:

System.InvalidCastException:无法转换类型的对象 System.Boolean 类型 System.Int16

我在 OnModelCreating 函数中添加了以下代码 sn-p:

            foreach (var entityType in modelBuilder.Model.GetEntityTypes())
                foreach (var property in entityType.GetProperties())
                    if (property.ClrType == typeof(bool) || property.ClrType == typeof(Boolean))
                        property.SetValueConverter(new BoolToZeroOneConverter<Int16>());

我错过了什么?

【问题讨论】:

  • 我认为你的模型和数据库类型不匹配。
  • 同意,确保您的 C# 模型和数据库字段具有相同的类型是有意义的。换一个合适的。那么你就没有问题了。
  • 我认为它是 MySql 包 看看这个github.com/abpframework/abp/issues/866
  • @AhmetArslan - 你应该添加你的评论作为答案 - 这是这个问题的正确答案

标签: c# mysql exception entity-framework-core


【解决方案1】:

试试belove代码:

[Required]
[Column(TypeName = "BIT")]
public bool IsDelete { get; set; }

【讨论】:

  • 请不要只发布代码作为答案,而是说明您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
【解决方案2】:

这通常是由实体类属性类型和数据库列类型不匹配造成的。

【讨论】:

    【解决方案3】:

    这是由于数据库架构和模型不匹配,我添加了以下内容来解决此问题:

                        else if (property.ClrType == typeof(Nullable<bool>) || property.ClrType == typeof(Nullable<Boolean>))
                            property.SetValueConverter(new BoolToZeroOneConverter<Nullable<Int16>>());
    

    【讨论】:

      【解决方案4】:

      这是 MySQL EF.Core 实现中的一个错误:bug 93028

      othersites 上,有人报告通过切换到Pomelo.EntityFrameworkCore.MySql 来解决问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-07
        • 1970-01-01
        • 2023-04-03
        • 2013-11-18
        • 2020-04-16
        • 2020-05-16
        • 1970-01-01
        相关资源
        最近更新 更多