简体   繁体   中英

Get data from cosmos db resulted null with entity framework

I have simple data in a container in cosmos db:

{
    "id": "fd81aacb-64eb-452b-a0bd-c0395aa8afb6",
    "thePartitionKey": "test"
}

When I try to list data with entity framework, it always returns null.

My DbContext looks something like this:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
   ..... //some configuration
   optionsBuilder.UseCosmos(endpoint, accountKey, dbName);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Test>()
                .ToContainer("theContainerID")
                .HasPartitionKey(e => e.thePartitionKey);
   public DbSet<Test>? Tests { get; set; }
}

The Model:

public class Test
{
   public string id { get; set; }
   public string thePartitionKey { get; set; }
}

The code:

public List<Test> GetDataTest(){
   var qry = context.Tests.ToList();
   return qry;
}

I have looked at some tutorials here , here , and here but it does not really seem to be different from my code.

What am I missing?

Using a similar example as shared by you in the question. In below screenshot you can see there is a single container in Cosmos DB having single record.

在此处输入图像描述

Solution:- As this container (theContainerId) stores a single document, there is no need of discriminator. In case the container has document of same entity type, we can use HasNoDiscriminator() method of Microsoft.EntityFrameworkCore package to get the record.

         modelBuilder.Entity<test>()
            .ToContainer("theContainerID")
            .HasPartitionKey(e => e.thePartitionKey)
            .HasNoDiscriminator();

Below is the screenshot of such an example.

在此处输入图像描述

As you can see, after modifying the modelBuilder the record is fetched.

在此处输入图像描述

It is explained in first link shared by you in question here at 22:16 secs.

Entity framework by default adds a discriminator value ("Discriminator": "{modelName}" in current scenario it will be test ) while creating the object, when you have multiple entity type of documents in the same cosmos DB container.

To get more information you can refer links available under reference section.

References:-

EF Core Azure Cosmos DB Provider

Azure CosmosDB + CRUD + Entity Framework Core - FREE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM