Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to track an entity of type because primary key property 'id' is null

After I upgraded to Asp.Net Core 3.0 I am getting the following error for my Identity class when attempting to create a user:

Unable to track an entity 'User' of type because primary key property 'id' is null.

Here User represents my extension of the Identity model.

This is the line of code where the error occurs:

var result = await _userManager.CreateAsync(user, password);
like image 673
Tom el Safadi Avatar asked Dec 02 '19 07:12

Tom el Safadi


People also ask

Why can't I track an entity of type with ID null?

[SOLVED] => Unable to track an entity of type because primary key... Unable to track an entity 'User' of type because primary key property 'id' is null. Here User represents my extension of the Identity model. This is due to breaking changes in EF Core 3.0 which can be found under this link:

Why can't I track an entity of type'yourmodalname'?

[Solved] Entity Framework Core (EF 6) Error: Unable to track an entity of type 'YourModalName' because primary key property 'id' is null. - ErnesTech [Solved] Entity Framework Core (EF 6) Error: Unable to track an entity of type 'YourModalName' because primary key property 'id' is null.

How to get pre-3 0 behavior of key properties?

The pre-3.0 behavior can be obtained by explicitly specifying that the key properties should use generated values if no other non-null value is set. For example, with the fluent API:


2 Answers

This is due to breaking changes in EF Core 3.0 which can be found under this link:

https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#string-and-byte-array-keys-are-not-client-generated-by-default

The problem can be solved by assigning a key manually like this:

// assign GUID to Id
user.Id = Guid.NewGuid().ToString();
var result = await _userManager.CreateAsync(user, password);

Another solution would be the following according to Microsoft:

The pre-3.0 behavior can be obtained by explicitly specifying that the key properties should use generated values if no other non-null value is set. For example, with the fluent API:

modelBuilder
    .Entity<Blog>()
    .Property(e => e.Id)
    .ValueGeneratedOnAdd();

Or with data annotations:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
like image 77
Tom el Safadi Avatar answered Oct 26 '22 03:10

Tom el Safadi


This solved the issue for me.

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        var keysProperties = builder.Model.GetEntityTypes().Select(x => x.FindPrimaryKey()).SelectMany(x => x.Properties);
        foreach (var property in keysProperties)
        {
            property.ValueGenerated = ValueGenerated.OnAdd;
        }
    }

like image 39
Zoidbergseasharp Avatar answered Oct 26 '22 03:10

Zoidbergseasharp