Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

azure cosmosdb - How to tell DocumentDB SDK to use camelCase during linq query?

Considering the document { "userName": "user1" } stored in the User collection, and the following User class:

public class User
{
        public string Id { get; set; }
        public string UserName { get; set; }
}

With the following JSON.net settings:

JsonConvert.DefaultSettings = () =>
{
    return new JsonSerializerSettings
    {
       ContractResolver = new CamelCasePropertyNamesContractResolver(),
    };
};

When I query with Linq as such:

var t = _client.CreateDocumentQuery<User>(_collection.SelfLink)
            .Where(u => u.UserName == "user1").AsDocumentQuery().ExecuteNextAsync();

t.Wait();

var users = t.Result;
var user = users.FirstOrDefault();

user is null. Changing the Document to have a pascal casing or the POCO to use a camel casing solves the issue. Of course I do not want any of those as I want my JSON objects and C# objects to be "standarized".

How can I tell the DocumentDB SDK to map my object's property names using camel casing, similar as JSON.net?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The DocumentDB LINQ provider does not pick up the JsonConvert.DefaultSettings. In general you can use the DefaultSettings to control camelCase, but for those properties you wish to use in a LINQ Where clause must have the name explicitly set using JsonProperty attribute on your DTO.

public class User
{
    public string Id { get; set; }

    [JsonProperty("userName")]
    public string UserName { get; set; }
}

Although a bit tedious and a good source for bugs, it seems to be your only option for now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...