如何使用 EF 核心在 SQLite 中创建自动增量列?

How to create Autoincrement column in SQLite using EF core?

我首先在 UWP and .NET Standard app. My model has an entity of type Primary Key integer which should be served as auto increment according to SQLite documentation 中使用 Entity Framework Core 2.0 for Sqlite 代码。但实际上,对于每一行,标识列的值都为 0。 请帮忙,因为我没有找到与此问题相关的帮助 material。

这是我的属性,没有任何数据注释。

public Int32 No { get; set; }

我用过fluentAPI

modelBuilder.Entity<TurnosGeneral>()
            .HasKey(c => new { c.No, c.Cod_Turno });

并在此处插入值

db.TurnosGenerals.Add(new TurnosGeneral { Cod_Turno = numeroTurnoTextBlock.Text });

db.SaveChanges();

对于插入的每一行,c.No 为 0。

My model has an entity of type Primary Key integer which should be served as auto increment

问题是属性问题是不是PK,而是复合PK的一部分,在这种情况下,它不被视为按惯例自动生成,如 EF Core 文档的 Generated Values Conventions 部分所述:

By convention, non-composite primary keys of type short, int, long, or Guid will be setup to have values generated on add. All other properties will be setup with no value generation.

您需要明确指定:

modelBuilder.Entity<TurnosGeneral>()
    .Property(e => e.No)
    .ValueGeneratedOnAdd();

更新: 以上是适用于大多数数据库的一般方法。但是 SQLite 支持 AutoIncrement only for column of type INTEGER PRIMARY KEY,因此这不是 EF Core 的限制。要么不使用自动增量,要么使其成为 non-composite PK。

看起来像一个错误。检查这个:https://github.com/aspnet/EntityFrameworkCore/issues/11961

我的解决方法:手动更改:.ValueGeneratedNever() 在我的 DBContext class.

我只是 运行 使用内存数据库中的 SQLite 进行测试。在我的例子中,我有一家公司 class,其主键字段名为 ContactCategoryId:

public class ContactCategory
{
    [Required]
    [Display(Name = "Contact category ID")]
    public int ContactCategoryId { get; set; }

而且我还使用了流畅的设置方法:

public void Configure(EntityTypeBuilder<ContactCategory> modelBuilder)
{
    modelBuilder.ToTable("CONTACT_CATEGORY", _schema);

    modelBuilder.HasKey(x => x.ContactCategoryId);

    modelBuilder.Property(x => x.ContactCategoryId)
        .HasColumnName(@"ContactCategoryID")
        //.HasColumnType("int") Weirdly this was upsetting SQLite
        .IsRequired()
        .ValueGeneratedOnAdd()
        ;

注释掉 .HasColumnType("int") 的行为我修复了错误。