提问人:Kenneth Clarke 提问时间:8/5/2022 最后编辑:Dale KKenneth Clarke 更新时间:8/5/2022 访问量:237
如何在 Entity Framework 中使用 SQL Server 序列
How to use SQL Server sequences in Entity Framework
问:
我正在开发一个 .NET Core 应用程序。在构建我的 API 时,我遇到了 post 端点的问题。我想使用数据库中存在的序列对象来保持 id 与其他表的一致性。
我在网上找到了一个看起来不错的解决方案。我将以下代码添加到我的 DbContext 中。
public DbSet<Developer> Developer { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Transaction>().ToTable("RtpTransaction");
modelBuilder.HasSequence("HIBERNATE_SEQUENCE");
modelBuilder.Entity<Developer>()
.ToTable("Developer")
.Property(x => x.Id)
.HasDefaultValueSql("NEXT VALUE FOR HIBERNATE_SEQUENCE");
}
然后,在我的控制器中,我设置了除 Id 以外的所有值,并希望它会自动用序列中的下一个值填充 Id 字段。
public ActionResult<DeveloperDto> CreateDeveloper(CreateDeveloperDto dto)
{
Developer newDeveloper = new()
{
CreatedDate = DateTime.Now,
CreatedBy = "RtpDeveloper",
LastUpdatedDate = DateTime.Now,
LastUpdatedBy = "RtpDeveloper",
DevShort = dto.DevShort,
DevMedium = dto.DevMedium,
Status = dto.Status,
DevClob = dto.DevClob
};
_context.Add(newDeveloper);
_context.SaveChanges();
return Ok(newDeveloper.AsDto());
}
但是,这不起作用,我收到一个错误,告诉我 Id 不能为 null。
我可能误解了我在这里阅读的文章
答: 暂无答案
评论