Skip to content

Concurrency exception when trying to insert entity with datetime2(0) key #27513

@clement911

Description

@clement911

Here is bug in EF6 Core.

Create an entity as follows:

public class QueryRun
    {
        [Column(TypeName = "datetime2(0)")]
        public DateTime StartedAt { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [NonDefault]
        public int Id { get; private set; }

        //other properties omitted for brevity
     }

Then try insert an entity

ctx.Add(new QueryRun
                {
                    StartedAt = DateTime.UtcNow,
                    //other properties omitted for brevity
                });
 await ctx.SaveChangesAsync();

This fails with the message: Expected 1 affected rows but got 0 rows!
After scratching my head for some time, I found the bug in the generated SQL code.

image

We can see that EF generated a param @p0 datetime2(7) instead of datetime2(0).
The issue is that the predicate [StartedAt] = @p0 returns FALSE because the parameter has milliseconds whereas the column is datetime2(0) and has no milliseconds.

Expected behaviour: when generating the p0 parameter, EF should use the same type as the column. That is, it should use datetime2(0) instead of datetime2(7). If I change the generated code to use datetime2(0), I can see that the generated ID is returned.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions