如何使用 EF 核心在 SQLite 中创建自动增量列? [英] How to create Autoincrement column in SQLite using EF core?

查看:17
本文介绍了如何使用 EF 核心在 SQLite 中创建自动增量列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我首先在我的 UWP 和 .NET Standard 应用.我的模型有一个主键整数类型的实体,它应该根据 SQLite 文档 用作自动增量.但实际上,Identity 列的每一行都将 0 作为值.请帮忙,因为我没有找到与此问题相关的帮助材料.

I am using Entity Framework Core 2.0 for Sqlite code first in my 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. But in real for every row that Identity column is getting 0 as a value. Please help because i found no helping material related to this issue.

这是我的财产,没有任何数据注释.

This is my property without any data annotaion.

public Int32 No { get;放;}

我用过 fluent API

I have used fluent API

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.

For every row inserted c.No is 0.

推荐答案

我的模型有一个主键整数类型的实体,它应该作为自动增量

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

问题在于所讨论的属性不是PK,而是复合PK的一部分,在这种情况下,按照惯例,它不被视为自动生成的,如生成值约定部分所述EF 核心文档:

The problem is that the property in question is not a PK, but a part of a composite PK, in which case it's not considered as auto generated by convention, as explained in the Generated Values Conventions section of the EF Core documentation:

按照惯例,short、int、long 或 Guid 类型的非复合主键将设置为在添加时生成值.所有其他属性将在不生成值的情况下进行设置.

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 仅适用于 INTEGER PRIMARY KEY 类型的列,因此这不是 EF Core 限制.要么不使用自动增量,要么使其成为非复合 PK.

Update: The above is the general approach applicable for most of the databases. But SQLite supports AutoIncrement only for column of type INTEGER PRIMARY KEY, hence this is not EF Core limitation. Either don't use auto increment or make it non-composite PK.

这篇关于如何使用 EF 核心在 SQLite 中创建自动增量列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆