使用 "Attach" 作为 Entity Framework 核心中的更新插入

Use "Attach" as an Upsert in Entity Framework Core

根据oneunicorn,

DbSet.Attach puts all entities in the graph into the Unchanged state. However, entities will be put in the Added state if they have store-generated keys (e.g. Identity column) and no key value has been set.

我在 "store-generated keys" 部分遇到问题。我的数据库是在 SMSS 中创建的,我的 table 有一个类型为 uniqueidentifier 的 Id 列,不为空。它是主键。但是我如何告诉 SMSS 它应该是商店生成的?当我 运行 导入时,C# 会发现吗? (特别是,如果可能的话,我想对内存数据库进行测试。)

使用 alter table SQL 语句设置列的默认值:

alter table myTable alter column myIdColumn default newid()

在 C# 方面,修饰您的 EF class 以指示该列的值是自动生成的:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
Guid myIdColumn { get; set; }

当您向其中一个 table 插入一行时,是数据库的 Id 列
table配置自动生成新的guid?使用 newid() 或 newsequentialid() ?后者更可取,因为它的索引更好。非顺序 guid 会影响插入繁重 tables.

中的性能

这里是一个 table 定义的例子,它有一个商店生成的 Id 列。

CREATE TABLE [dbo].[MyTable] (
    [Id] [uniqueidentifier] NOT NULL PRIMARY KEY CLUSTERED CONSTRAINT [PK_MyTable_Id] DEFAULT (newsequentialid()) 
)

然后将像这样指定 EF 模型...

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }