Home > OS >  Get data from cosmos db resulted null with entity framework
Get data from cosmos db resulted null with entity framework

Time:01-17

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 enter image description here

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.

enter image description here

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

enter image description here

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

  • Related