【发布时间】:2021-12-14 14:05:50
【问题描述】:
我在使用实体框架核心插入具有默认值列的记录时遇到了一个奇怪的问题。 有没有其他方法可以获得预期的行为,我错过了什么愚蠢的东西吗?
tldr:将 int 属性 = 0 或 bool 设置为 true 会导致使用默认值 新字符串的 string.empty 给出 ORA-01400: cannot insert NULL (这似乎是 oracle 的事情)
场景: 使用迁移添加新列并添加新记录会导致正常行为(插入默认值)
仅添加一条新记录 oldField 提供= OK
"ID" : 6, "OLDFIELD" : "ef test 1", "NEWINT" : 5, "NEWSTRING" : "def", "NEWBOOLFALSE" : 0, "NEWBOOLTRUE" : 1
添加与 .Net 默认值不同的值也可以
"ID" : 12, "OLDFIELD" : "ef test all set", "NEWINT" : 42, "NEWSTRING" : "string here", "NEWBOOLFALSE" : 1, "NEWBOOLTRUE" : 1
现在的问题 当您为 int 指定 0 而为 bool 指定 false 时
var test = new TestDef()
{
OldField = "ef bad test",
NewInt = 0,
NewBoolFalse = false,
NewBoolTrue = false
};
_womaDbContext.Add(test);
await _womaDbContext.SaveChangesAsync();
你会得到"ID" : 36, "OLDFIELD" : "ef bad test", "NEWINT" : 5, "NEWSTRING" : "def", "NEWBOOLFALSE" : 0, "NEWBOOLTRUE" : 1
NewString = string.Empty 给出 oracle 异常 ORA-01400: cannot insert NULL(这似乎是 oracle 的事情)
插入查询正常
INSERT INTO WOMA_SCHEMA.TESTDEF
(ID, OLDFIELD, NEWINT, NEWBOOLFALSE, NEWBOOLTRUE)
VALUES("WOMA_SCHEMA"."ISEQ$$_42048".nextval, 'sql empty',0, 0,0);
这使得不进行更新就无法在 NEWBOOLTRUE 中插入假值或在 NEWINT 中插入 0
testclass(DbContext OnModelCreating 调用 TestDef.OnModelCreating(modelBuilder)):
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Test.Model
{
[Table("TESTDEF")]
public class TestDef
{
[Column("ID")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Column("OLDFIELD")]
public string OldField { get; set; }
[Required]
[Column("NEWINT")]
public int NewInt { get; set; }
[Required]
[Column("NEWSTRING")]
public string NewString { get; set; }
[Required]
[Column("NEWBOOLTRUE")]
public bool NewBoolTrue { get; set; }
[Required]
[Column("NEWBOOLFALSE")]
public bool NewBoolFalse { get; set; }
public static void OnModelCreating(ModelBuilder modelBuilder)
{
// Default values
modelBuilder
.Entity<TestDef>()
.Property(e => e.NewInt)
.HasDefaultValue(5);
modelBuilder
.Entity<TestDef>()
.Property(e => e.NewString)
.HasDefaultValue("def");
modelBuilder
.Entity<TestDef>()
.Property(e => e.NewBoolTrue)
.HasDefaultValue(true);
modelBuilder
.Entity<TestDef>()
.Property(e => e.NewBoolFalse)
.HasDefaultValue(false);
}
}
}
【问题讨论】:
标签: c# oracle entity-framework-core