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'
)
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With