问题
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.)
回答1:
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; }
回答2:
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; }
来源:https://stackoverflow.com/questions/48613068/use-attach-as-an-upsert-in-entity-framework-core