Azure Cosmos DB (EF/Core) - Camel Case Property Names

Viewed 2061

I have a .NET Core 3.1 API Project which has Cosmos DB storage being handled via Entity Framework (Microsoft.EntityFrameworkCore.Cosmos - v3.1.5).

I have a database model:

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class BikeRental
{
    [JsonProperty(PropertyName = "id")]
    [Key]
    public Guid Id { get; set; }

    [JsonProperty(PropertyName = "bikeId")]
    public string BikeId { get; set; }

    [JsonProperty(PropertyName = "shopId")]
    public string ShopId { get; set; }
}

Upon saving to the CosmosDB database, the columns are being serialised using the class property names, ignoring the 'PropertyName' attribute. For example, if 'bikeId' is changed to 'testBikeId' it is written as 'BikeId' still.

{
    "Id": "192dfdf4-54cb-4290-a478-7035518983ca",
    "BikeId": "eb65b93b-17d3-4829-9729-d48c029211fe2",
    "ShopId": "636c08c4-600d-458a-98b7-8d312b8c18d2",

    "_rid": "2QZIAMVYbVQBAAAAAAAAAA==",
    "_self": "dbs/2QZIAA==/colls/2QZIAMVYbVQ=/docs/2QZIAMVYbVQBAAAAAAAAAA==/",
    "_etag": "\"00000000-0000-0000-4627-f721b0e701d6\"",
    "_attachments": "attachments/",
    "_ts": 1592564051
}

Any help or suggestions on how to resolve this would be much appreciated!

Edit: The saving of the object to Cosmos is performed via:

var response = _context.BikeRentals.Add(obj)
_context.SaveChanges();
3 Answers

Use Fluent API for model configuration in OnModelCreating method:

modelBuilder.Entity<BikeRental>().Property(x => x.Id).ToJsonProperty("id");
modelBuilder.Entity<BikeRental>().Property(x => x.BikeId).ToJsonProperty("bikeId");
modelBuilder.Entity<BikeRental>().Property(x => x.ShopId).ToJsonProperty("shopId");

For EF mapping use ColumnAttribute or the fluent configuration in OnModelCreating is used.

In the case of Cosmos you may want the names in the database to be the same as the names when you serialize for sending to the client, but in the general case your entities may map to the database differently than for JSON serialization.

You should use the Fluent API and iterate all the entity types, and properties an apply the Pascal-to-Camel-Case transformation.

The problem with the id is due to not adding

  modelBuilder.Entity<BikeRental>().HasNoDiscriminator();

If you add this it should just create the id alone

Related