dotnet / dotnet/EntityFramework.Docs
Are you sure that the keys of entities in Added state have been set?
- Dominant language
- Mermaid
- Stars
- 1.7k
- Forks
- 2k
- Avg merge
- 7d 23h
- Merged PRs (30d)
- 16
Description
According to the documentation,

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);
}
```

---
#### 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
Assessment
This issue has not been assessed yet.