Use "Attach" as an Upsert in Entity Framework Core

c# database-first entity-framework-core ssms


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 (e.g. 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.)

2/4/2018 9:13:34 PM

Accepted Answer

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:

Guid myIdColumn { get; set; }
2/4/2018 9:26:08 PM

Popular Answer

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...

public Guid Id { get; set; }

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow