我们使用的是.Net Core 1,我们迁移到预览2(都是实体).
在迁移之前,我们曾经在Entity Framework中为布尔值设置默认值,如下所示:
在迁移之前,我们曾经在Entity Framework中为布尔值设置默认值,如下所示:
modelBuilder.Entity<Customer>() .ToTable("Customer") .Property(a => a.Active) .HasDefaultValue(true);
迁移后,我们没有更改任何内容,但现在我们在实体尝试创建此表时收到错误.
看起来它试图创建一个默认值为字符串,如“True”,而不是像以前一样.
有谁知道发生了什么变化?
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’.
脚本生成:
CREATE TABLE `Customer` ( `Id` int NOT NULL,`Active` bit NOT NULL DEFAULT 'True' )
解决方法
我遇到了同样的问题.但是,在我自己研究这个问题之后,我发现了一个相当棘手的
workaround.它似乎
如果你将bool值设置为可以为空,那么使用fluent api设置默认值,你应该没问题.它不完美,但它的工作原理:
public class Year { public int Id { get; set; } public string label { get; set; } public int year { get; set; } public bool? active { get; set; } }
然后,在您的数据上下文中,设置默认值:
modelBuilder.Entity<Year>() .Property("active") .HasDefaultValue(true);
将新记录插入数据库时,不需要在对象声明中指定boolean属性.下面,2017年的默认值为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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。