[英]Generate auto-increment int column in MariaDB with EFCore
The Problem: 问题:
I'm trying to create a table with efcore in .netcore 2.2 using codefirst having an auto-increment integer primary key starting at 0. All solutions i found result in either an error on adding migration or the auto-incrementing works but start at int.MinValue. 我正在尝试使用codefirst在.netcore 2.2中使用efcore创建一个表,该表具有从0开始的自动递增整数主键。我发现的所有解决方案都会导致添加迁移或自动递增工作时出错,但从int开始.MinValue。
All the following solutions have been tried seperated, not combined: 以下所有解决方案均已单独尝试,未结合使用:
Solution 1: 解决方案1:
Do nothing. 没做什么。 Just let efcore do its default thing.
只需让efcore进行默认操作即可。
-> The column auto-increments but starts at int.MinValue ->列自动增加,但从int.MinValue开始
Solution 2: 解决方案2:
setting annotation "[DatabaseGenerated(DatabaseGeneratedOption.Identity)]"
on primary key. 在主键上设置注释
"[DatabaseGenerated(DatabaseGeneratedOption.Identity)]"
。
-> The column auto-increments but starts at int.MinValue ->列自动增加,但从int.MinValue开始
Solution 3: 解决方案3:
modelBuilder.Entity<User>()
.Property(u => u.Id)
.ValueGeneratedOnAdd();
-> The column auto-increments but starts at int.MinValue ->列自动增加,但从int.MinValue开始
Solution 4: 解决方案4:
modelBuilder.HasSequence<int>("User_seq")
.StartsAt(0)
.IncrementsBy(1);
modelBuilder.Entity<User>()
.Property(u => u.Id)
.HasDefaultValueSql("NEXT VALUE FOR User_seq");
-> Adding a migration fails with an error: ->添加迁移失败,并显示以下错误:
"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SEQUENCE User_seq START WITH 0 INCREMENT BY 1' at line 1"
Solution 5: 解决方案5:
changing the datatype of Id to uint. 将Id的数据类型更改为uint。
-> The column auto-increments but starts at int.MaxValue ->列自动增加,但从int.MaxValue开始
My User entity: 我的用户实体:
public class User
{
public int Id { get; set; }
public string FirstName{ get; set; }
public string LastName { get; set; }
}
Provider used: Pomelo.EntityFrameworkCore.MySql 使用的提供程序: Pomelo.EntityFrameworkCore.MySql
To clarify my question: How do I create an auto-incrementing integer primary key column starting at 0 incrementing by 1 in MariaDB using efcore codefirst? 要澄清我的问题:如何使用efcore codefirst在MariaDB中创建从0开始递增1的自动递增整数主键列?
You cannot. 你不能。
MariaDB (MySQL) treats 0 as meaning to create a new AUTO_INCREMENT
value. MariaDB(MySQL)将0视为创建新的
AUTO_INCREMENT
值的含义。
Do not assume properties of AUTO_INCREMENT
that it does not provide. 不要假定它没有提供的
AUTO_INCREMENT
属性。 It only says that each new value will be different than the existing values. 它仅表示每个新值都将与现有值不同。
Probably int.MinValue
is some big negative value (-2^31). int.MinValue
可能是一个较大的负值(-2 ^ 31)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.