Entity Framework Core DbContext.SaveChanges throws System.InvalidCastException: Unable to cast object of type System.Boolean to type System.Int16

c# entity-framework-core exception mysql

Question

I am using .net core 2.2 with entity framework using MySql.Data.EntityFramework.Core. Bump into this exception when I do the following:

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

Exception:

System.InvalidCastException: Unable to cast object of type System.Boolean to type System.Int16

I have added the following code snippet into OnModelCreating function:

            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>());

What do I miss?

1
0
6/3/2019 10:30:28 AM

Accepted Answer

This was due to database schema and model mismatch and I added the following to fix the issue:

                    else if (property.ClrType == typeof(Nullable<bool>) || property.ClrType == typeof(Nullable<Boolean>))
                        property.SetValueConverter(new BoolToZeroOneConverter<Nullable<Int16>>());
1
6/5/2019 4:06:33 AM

Popular Answer

try belove code:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow