Entity Framework Core, unable to set HasName on PrimaryKey
Asked Answered
K

2

7

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://learn.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

Kansas answered 8/6, 2020 at 7:21 Comment(3)
Did you get this resolved or are you still looking for a solution? learn.microsoft.com/en-us/ef/core/providers/cosmos/…Rarefaction
I am unable to resolve this @MikeUbezziMSFT any pointers appreciated.Gisellegish
I am no longer with Microsoft. I hope you are able to or have found a resolution for this. Again, apologize for the delay in responding with an update.Rarefaction
G
0

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://mcmap.net/q/467014/-unable-to-track-an-entity-of-type-because-primary-key-property-39-id-39-is-null-duplicate.

Gelatin answered 19/11, 2020 at 16:55 Comment(0)
D
0
modelBuilder.Entity<TestModel>(entity=> entity.Property(x=>x.ID).HasColumnName("id"))
Deadhead answered 24/8, 2022 at 12:16 Comment(1)
This answer was reviewed in the Low Quality Queue. Here are some guidelines for How do I write a good answer?. Code only answers are not considered good answers, and are likely to be downvoted and/or deleted because they are less useful to a community of learners. It's only obvious to you. Explain what it does, and how it's different / better than existing answers.Haemic

© 2022 - 2024 — McMap. All rights reserved.