使用 Entity Framework Core 在部分主键上自动递增

编程入门 行业动态 更新时间:2024-10-28 12:17:28
本文介绍了使用 Entity Framework Core 在部分主键上自动递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经使用 EF Core fluent API 声明了以下模型:

I have declared the following model using the EF Core fluent API:

modelBuilder.Entity<Foo>() .HasKey(p => new { p.Name, p.Id });

当我在 PostgreSQL 中创建数据库时,两个字段都被标记为主键,但 Id 字段未标记为自动增量.我也尝试添加

Both fields are marked as the primary key when I create the database in PostgreSQL but the Id field is not marked as auto increment. I have also tried to add

[Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

到 Foo 下的 Id 字段,而不会对迁移代码产生任何影响.虽然是PPK,但有没有办法制作Id AI?

to the Id field under Foo without it making any difference on the migration code. Is there a way to make the Id AI although it is a PPK?

推荐答案

好吧,那些数据注解应该可以解决问题,也许与 PostgreSQL Provider 有关.

Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.

来自 EF Core 文档:

根据所使用的数据库提供程序,可能会生成值客户端通过 EF 或在数据库中.如果该值是由数据库,那么 EF 可能会在您添加实体时分配一个临时值到上下文.这个临时值将被替换为SaveChanges 期间数据库生成的值.

Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges.

您也可以尝试使用此 Fluent Api 配置:

You could also try with this Fluent Api configuration:

modelBuilder.Entity<Foo>() .Property(f => f.Id) .ValueGeneratedOnAdd();

但正如我之前所说,我认为这与数据库提供程序有关.尝试向您的数据库添加一个新行,稍后检查是否为 Id 列生成了一个值.

But as I said earlier, I think this is something related with the DB provider. Try to add a new row to your DB and check later if was generated a value to the Id column.

更多推荐

使用 Entity Framework Core 在部分主键上自动递增

本文发布于:2023-10-16 00:47:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1495982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主键   Entity   Framework   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!