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:-
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.