加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Entitiy Framework核心预览2 – 布尔值的默认值

发布时间:2020-12-15 21:07:22 所属栏目:百科 来源:网络整理
导读:我们使用的是.Net Core 1,我们迁移到预览2(都是实体). 在迁移之前,我们曾经在Entity Framework中为布尔值设置默认值,如下所示: modelBuilder.EntityCustomer() .ToTable("Customer") .Property(a = a.Active) .HasDefaultValue(true); 迁移后,我们没有更改
我们使用的是.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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读