使用“附加”作为Entity Framework Core的Upsert [英] Use "Attach" as an Upsert in Entity Framework Core

查看:96
本文介绍了使用“附加”作为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; }

这篇关于使用“附加”作为Entity Framework Core的Upsert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆