1

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?

4
  • 2
    I think your model and database type mismatch. Jun 3, 2019 at 9:44
  • Agreed, it would make sense to ensure your C# model and your database fields have the same types. Change whichever one is appropriate. Then you'll have no issues.
    – ADyson
    Jun 3, 2019 at 10:34
  • I think its the MySql package Look into this github.com/abpframework/abp/issues/866
    – Assaf Our
    Jun 3, 2019 at 11:28
  • 1
    @AhmetArslan - You should have added your comment as an answer - its the correct answer for this question Jun 3, 2019 at 13:39

4 Answers 4

4

try belove code:

[Required]
[Column(TypeName = "BIT")]
public bool IsDelete { get; set; }
1
  • 1
    Please don't post only code as an answer, but include an explanation what your code does and how it solves the problem of the question. Answers with an explanation are generally of higher quality, and are more likely to attract upvotes. Oct 26, 2019 at 6:49
1

This is a bug in the MySQL EF.Core implementation: bug 93028.

On other sites, people have reported fixing the issue by switching to Pomelo.EntityFrameworkCore.MySql.

1

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

This is typcally caused by mismatch between entity class property type and database column type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.