Entity Framework Core EF formatting datetime saved as enstring type in Azure CosmoDB

936 Views Asked by At

I am experiencing an issue fetching data from CosmosDB using EF Core v3.1.

Basically I have an entity as follows:

public class Test
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
}

EF setup data model is pretty basic.

When I save a document in CosmosDB using EF, the document is as follows:

{
  "Name": "NameTest",
  "Type": "TypeTest",
  "Value": "2021-04-15T15:21:48.8065967Z"
}
    

When I fetch all documents from CosmosDB using EF ToListAsync method in code, the result brings the Value property as follows:

04/15/2021 15:22:01

Considering the Value property is a string type, (not DateTime), I would like EF not to format the value and leave it as is.

I could not find any information, perhaps how to disable that option, even using "Conversion" option available in the EF model creating method.

Could anyone shed some light here and perhaps find a way to to keep the same value from CosmosDB?

Cheers,

1

There are 1 best solutions below

2
On

Per my searching, that's really no doc to tell the reason for auto format(string -> datetime) the query result and how to disable this kind of convert. And I also met the same problem as yours.

According to my testing result, I found that whether I set public string Value { get; set; } or public Datetime Value { get; set; }, I always got the response like mm/dd/yyyy hh:mm:ss, it can show a correct date time result but in a different format with the string stored in cosmosdb. I have no other ways but to change the format of the querying result of Linq-to-entity.

using (var context = new OrderContext())
            {
                var order = context.Orders.Where(s => s.PartitionKey == "2").FirstOrDefault<Order>();
                DateTime aaa = order.Value;
                string b = aaa.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ");
                Console.WriteLine($"result is: {b}");
                Console.WriteLine();
            }

enter image description here