Entity Framework Core, unable to set HasName on PrimaryKey

Viewed 905

I am trying to access a CosmosDB collection using Entity Framework Core.

My DB has various data, but the primary key is 'id' My Model has a subset of this, but uses 'Id' instead of 'id'.

I have checked that I am able to read/write to a test DB where it includes a copy of 'id' as 'Id'. This causes no issues.

As far as i can read in https://docs.microsoft.com/en-us/ef/core/modeling/indexes it should be possible to set the 'HasName' property.

[DataContract]
[Serializable]
public class TestModel
{
    [DataMember] 
    [JsonProperty("id")] 
    public string Id { get; set; }

    [DataMember] 
    public string Pid { get; set; }
}


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<TestModel>().ToContainer("TestModel");
    modelBuilder.Entity<TestModel>().HasPartitionKey(x => x.Pid);
    modelBuilder.Entity<TestModel>().HasNoDiscriminator();

    modelBuilder.Entity<TestModel>().HasKey(b => b.Id).HasName("id");
}

Using this, i still get an error.

InvalidOperationException: Unable to track an entity of type 'TestModel' because primary key property 'Id' is null.

I have also in trial and error, attempted to use. - HasName + HasKey / HasIndex - HasColumnName + Property

2 Answers

This seems to be caused by breaking changes in EF Core 3.0, these can be found here.

You can probably solve it with the data annotation [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

public class TestModel
{
    [DataMember] 
    [JsonProperty("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string Id { get; set; }
(...)

and if that doesn't work, a second solution would be to assign a GUID to the id. See this discussion for more info on that https://stackoverflow.com/a/59134407/14344821.

modelBuilder.Entity<TestModel>(entity=> entity.Property(x=>x.ID).HasColumnName("id"))
Related