Use “Attach” as an Upsert in Entity Framework Core

房东的猫 提交于 2020-03-03 08:04:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!