How can i set partition key from cosmosdb collection through entity framework core code first approach?

.net-core asp.net-core azure azure-cosmosdb entity-framework-core

Question

public class TaxathandDbContext : DbContext { public TaxathandDbContext(DbContextOptions options) : base(options) { Database.EnsureCreated(); }

    protected TaxathandDbContext()
    {
        Database.EnsureCreated();
    }

    public DbSet<Address> Address { get; set; }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {                    
                OneCollectionPerDbSet(modelBuilder);
            }

    private void OneCollectionPerDbSet(ModelBuilder modelBuilder)
    {
        var dbSets = typeof(TaxathandDbContext).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => p.PropertyType.IsGenericType && typeof(DbSet<>).IsAssignableFrom(p.PropertyType.GetGenericTypeDefinition()));
        foreach (var dbSet in dbSets)
        {`enter code here`
            var metadata = modelBuilder.Entity(dbSet.PropertyType.GetGenericArguments()[0]).Metadata;
            metadata.Cosmos().ContainerName = dbSet.Name;
        }
    }
}
1
3
10/16/2019 11:14:28 AM

Popular Answer

According to Microsoft documentation it is pretty simple. One important thing to note: your partition keys must be string or converted to string!

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        modelBuilder.Entity<TodoItem>()
            .HasPartitionKey(o => o.Id);
}
2
1/4/2020 12:03:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow