Skip to content

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

@mauler2025

Description

@mauler2025

According to the documentation,

trackedid

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.

private static async Task<IResult> Add(StudentEnrollmentDbContext ctx, Course course, ILogger<Program> 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


Document Details

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions