Kon*_*rad 6 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我们什么时候应该更喜欢使用HasDefaultValue类中的默认值而不是初始化类内的默认值?
public class Foo
{
public int Bar { get; set; } = 1337;
// or inside constructor...
// public Foo { Bar = 1337; }
}
Run Code Online (Sandbox Code Playgroud)
或者我们应该两者都做?但在这种情况下,HasDefaultValue似乎是多余的。这似乎是一个只能选择 1 个选项的选择。
Onu*_*kir -2
我不知道我是否理解正确,但您可以使用 getter/setter 方法为不同的属性设置不同的默认值,如下所示,
private int _bar = 1337;
public int Bar{
get{
return _bar;
}
set{
_bar = value;
}
}
private int _secondBar = 1234;
public int SecondBar{
get{
return _secondBar;
}
set{
_secondBar = value;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6050 次 |
| 最近记录: |