c# - HasDefaultValue 与从构造函数设置默认值

标签 c# entity-framework-core ef-core-2.1

使用 EF Core 时,我们可以在属性上设置默认值。

public class Foo
{
    public int Bar { get; set; }
}

public class FooConfiguration : IEntityTypeConfiguration<Foo>
{
    public void Configure(EntityTypeBuilder<Foo> builder)
    {
        builder.Property(s => s.Bar).HasDefaultValue(1337);
    }
}

我们什么时候更喜欢使用 HasDefaultValue过度初始化类内的默认值?
public class Foo
{
    public int Bar { get; set; } = 1337;

    // or inside constructor...
    // public Foo { Bar = 1337; }
}

还是我们应该两者都做?但在这种情况下,HasDefaultValue似乎多余。这似乎是一种选择,您只能选择 1 个选项。

最佳答案

HasDefaultValue()方法指定

The default value of a column is the value that will be inserted if a new row is inserted but no value is specified for the column.



如果没有另外指示,在类中使用默认值初始化属性将使该类初始化的所有对象都具有指定的默认值。在您的情况下,这意味着即使未附加的对象也将具有默认值,同时使用 HasValue()将对象插入数据库时​​将使用方法。这也意味着,如果在添加 HasDefaultValue() 时数据库中已经有空值方法,它们不会被覆盖。

关于c# - HasDefaultValue 与从构造函数设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53042133/

相关文章:

c# - ReSharper 有没有一种方法可以抑制一个文件中的所有错误/警告?

c# - 将 SQLite 数据库同步到 SQL Server

c# - 在 .net core 上创建 EF 迁移时出现 System.IO.FileNotFoundException

asp.net-mvc - 覆盖默认身份表名称

c# - Linq 搜索原理和带有 OR 语句的子集合

c# - 使用种子属性自定义 AutoFixture 构建器

c# - 选择消息传递解决方案

c# - 您的启动项目未引用 Microsoft.EntityFrameworkCore.Design

c# - 在 System.ComponentModel 默认值属性中将 DateTime 属性的默认值设置为 DateTime.Now

ef-core-2.1 - 尽管急切获取 "attempt was made to lazy-load navigation property on detached entity"