c# – Entitiy Framework核心预览2 – 布尔值的默认值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – Entitiy Framework核心预览2 – 布尔值的默认值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1660字,纯文字阅读大概需要3分钟。
内容图文
![c# – Entitiy Framework核心预览2 – 布尔值的默认值](/upload/InfoBanner/zyjiaocheng/768/36474202eca54599914775ea983adafe.jpg)
我们使用的是.Net Core 1,我们迁移到预览2(都是实体).
在迁移之前,我们曾经在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();
内容总结
以上是互联网集市为您收集整理的c# – Entitiy Framework核心预览2 – 布尔值的默认值全部内容,希望文章能够帮你解决c# – Entitiy Framework核心预览2 – 布尔值的默认值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。