Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure EF Core with Cosmos DB to store ICollection of string

Tags:

Entity framework has some nice documentation about Embedding entities but I cannot figure out how to embed a simple string array IEnumerable<string>.

Sample class

public class Post {
  public string Id {get;set;}
  public string Content {get;set;}
  public IEnumerable<string> Tags {get;set;}
}

This should be saved in cosmos as:

{
  "id": "xxx",
  "content": "long content here",
  "tags": ["tag1", "tag2"],
  ...
}

I know I have to configure something in the OnModelCreating(ModelBuilder modelBuilder) of the Context. But I cannot get it setup correctly.

I've tried to following options (and several other ToJsonProperty methods):

  • modelBuilder.Entity<Post>().OwnsMany(p => p.Tags);
  • modelBuilder.Entity<Post>().OwnsMany<string>(p => p.Tags);

Eventually I want to be able to query based on those tags, any help or pointers in the right direction are greatly appreciated!

I also found this answer but converting the array to a comma separated string would defeat the purpose (since that doesn't allow us to query those posts).

Someone else asked roughly the same question on the Microsoft forums, where a Microsoft employee states that in pure CosmosDB it is possible to embed a string array in cosmos.

like image 409
Stephan Avatar asked Nov 13 '20 10:11

Stephan


1 Answers

I recently tried to find an answer to the same question. Did not find a good solution, so I created a new model

public class Tag
{
   public string Name { get; set; }
}

public class Post
{
  ...
  public IEnumerable<Tag> Tags { get; set; }
}

...
modelBuilder.Entity<Post>().OwnsMany(p => p.Tags);
like image 115
Roman Marusyk Avatar answered Oct 11 '22 21:10

Roman Marusyk