简体   繁体   中英

Use “Attach” as an Upsert in Entity Framework Core

According to 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 (eg Identity column) and no key value has been set.

I'm having trouble with the "store-generated keys" part. My database was created in SMSS, and my table has an Id column of type uniqueidentifier, not null. It is the primary key. But how do I tell SMSS it should be store-generated? And will C# find out about that when I run an import? (In particular, I want to do tests on an in-memory database, if possible.)

Set the default value of the column using the alter table SQL statement:

alter table myTable alter column myIdColumn default newid()

On the c# side, decorate your EF class to indicate that the value for that column is auto-generated:

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

When you insert a row into one of your tables is the Id column of the database
table configured to automatically generate a new guid? using newid() or newsequentialid() ? The latter is preferable as it indexes better. Non sequential guids can impact performance in insert heavy tables.

Here is an example of a table definition that has a store generated Id column.

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

The EF model would then be specified like so...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM