【发布时间】:2020-12-26 09:28:53
【问题描述】:
我用主键创建一个表。
我尝试使用 entityframework6 插入新数据,但会出现 23502 错误。
但我在插入之前将默认值添加到列中。
我不明白为什么会出现这个错误。
表 DDL:
CREATE TABLE ERRORLOG(
id numeric NOT NULL,
message varchar(50) NULL,
CONSTRAINT pterrorlog_pk PRIMARY KEY (id)
);
型号:
public partial class ERRORLOG
{
[Key]
[Column(Order = 0)]
public long ID { get; set; } = DateTimeOffset.Now.ToUnixTimeMilliseconds();
public string MESSAGE { get; set; }
}
功能:
using (DbContext Db as new DbContext)
using (TransactionScope transactionScope = new TransactionScope())
{
ERRORLOG iLog = new ERRORLOG();
iLog.MESSAGE = Message;
Db.ERRORLOG.Add(iLog);
Db.SaveChanges(); //Get 23502 error
}
这里是插入脚本,好像没有插入id,这是为什么呢?
INSERT INTO "pterrorlog"("message") VALUES (@p_0) RETURNING "id"
编辑:
在模型上添加此脚本后,它现在可以正常工作了。
public partial class ERRORLOG
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long ID { get; set; } = DateTimeOffset.Now.ToUnixTimeMilliseconds();
public string MESSAGE { get; set; }
}
【问题讨论】:
-
错误信息很清楚。您正在尝试将
NULL插入到非空列id。也请显示您的插入语句。 -
@ArunPalanisamy 我更新了语句,好像没有插入 id 列,这是为什么呢?
-
我可以看到您没有将任何值传递给
id。它是一个自动增量列吗? -
@ArunPalanisamy 我使用这个脚本来设置它的值:public long ID { get;放; } = DateTimeOffset.Now.ToUnixTimeMilliseconds();
标签: postgresql entity-framework