Search code examples
c#ssmsentity-framework-coredatabase-first

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


Solution

  • 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; }