dotnet / dotnet/EntityFramework.Docs

Are you sure that the keys of entities in Added state have been set?

Open
#4,030 1 comment 0 reactions 0 assignees View on GitHub
area-change-tracking
Dominant language
Mermaid
Stars
1.7k
Forks
2k
Avg merge
7d 23h
Merged PRs (30d)
16

Description

According to the documentation,

![trackedid](https://user-images.githubusercontent.com/50270635/190344462-5bd5cb19-5ccf-4989-b8a9-bb96f86f8c40.png)

keys are set as soon as entities are tracked by the context, even if the entity is in the `Added` state.

In the following code, I found the claim is not correct.
Right before `SaveChangeAsync()` is invoked but after `AddAsync()` is invoked, the entity is in `Added` state and the `IsKeySet` is `False` (rather than `True` as the documentation claims). It means the key has not been set yet.

```csharp
private static async Task Add(StudentEnrollmentDbContext ctx, Course course, ILogger logger)
{
var added = await ctx.Courses.AddAsync(course);
logger.LogError(added.Entity.Id.ToString()); // output: 0
logger.LogError(added.State.ToString()); // output: Added
logger.LogError(added.IsKeySet.ToString()); // output: False
await ctx.SaveChangesAsync();
logger.LogError("=========================");
logger.LogError(added.Entity.Id.ToString()); // output: 1006
logger.LogError(added.State.ToString()); // output: Unchanged
logger.LogError(added.IsKeySet.ToString()); // output: True
return Results.CreatedAtRoute(nameof(Get), new { id = added.Entity.Id }, added.Entity);
}
```

![log](https://user-images.githubusercontent.com/50270635/190346046-70e53e65-8f89-4ae9-a273-14e347b37cf7.png)

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: b9826f28-46b2-e845-f1bf-5cbc2d940208
* Version Independent ID: 9c4a46cf-daa2-0e14-7ff1-c195db237cd0
* Content: [Disconnected Entities - EF Core](https://docs.microsoft.com/en-us/ef/core/saving/disconnected-entities)
* Content Source: [entity-framework/core/saving/disconnected-entities.md](https://github.com/dotnet/EntityFramework.Docs/blob/main/entity-framework/core/saving/disconnected-entities.md)
* Product: **entity-framework**
* Technology: **entity-framework-core**
* GitHub Login: @ajcvickers
* Microsoft Alias: **avickers**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.