Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entitiy Framework Core preview 2 - default value for boolean

We were using .Net Core 1 and we migrated to Preview 2 (both with Entity). Before migration, we used to set a default value for a boolean in Entity Framework like this:

modelBuilder.Entity<Customer>()
  .ToTable("Customer")
  .Property(a => a.Active)
  .HasDefaultValue(true);

After migration, we didn't change anything but now we are getting an error when entity tries to create this table. It looks like it is trying to create a default value as string like "True" and not as a bit, like before.

Does anyone knows what have changed?

ERROR on update-database

The 'bool' property 'Active' on entity type 'Customer' is configured with a database-generated default. This default will always be used when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead so that the default will only be used when the property value is 'null'.

Script generated:

CREATE TABLE `Customer` (
    `Id` int NOT NULL,
    `Active` bit NOT NULL DEFAULT 'True'
   )
like image 251
Andre Quedinho Avatar asked Nov 07 '22 19:11

Andre Quedinho


1 Answers

I have encountered the same issue. However, I have found a rather tricky workaround after researching this issue myself. It seems

If you set your bool value to be nullable, then use the fluent api to set the default, you should be fine. Its not perfect, but it works:

public class Year
{
        public int Id { get; set; }
        public string label { get; set; }
        public int year { get; set; }
        public bool? active { get; set; }
}

Then, in your data context, set the default value:

            modelBuilder.Entity<Year>()
            .Property("active")
            .HasDefaultValue(true);

When you insert new records into the database, you won't need to specify the boolean property in your object declaration. Below, the year 2017 will have a default value of true.

            var newYears = new List<Year>();

            newYears.Add(new Year { label = "2019", year = 2019, active = false });
            newYears.Add(new Year { label = "2018", year = 2018, active = true });
            newYears.Add(new Year { label = "2017", year = 2017});
            _context.Years.AddRange(newYears);
            _context.SaveChanges();
like image 152
Rick B Avatar answered Nov 15 '22 13:11

Rick B