使用“附加”作为Entity Framework Core的Upsert
根据 oneunicorn ,
DbSet.Attach将图中的所有实体置于未更改状态。但是,如果实体具有商店生成的键(例如,身份列),并且未设置键值,则它们将处于已添加状态。
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.
我在商店生成的密钥部分遇到了麻烦。我的数据库是在SMSS中创建的,并且我的表的ID列的类型为uniqueidentifier,而不是null。它是主键。但是如何告诉SMSS应该由商店生成?当我运行导入时,C#会发现关于此的信息吗? (特别是,如果可能的话,我想在内存数据库中进行测试。)
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.)
设置默认值使用 alter表
SQL语句的列:
Set the default value of the column using the alter table
SQL statement:
alter table myTable alter column myIdColumn default newid()
在c#端,装饰EF类以指示用于该列是自动生成的:
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; }