Complex objects with Cosmos DB
I have a complex object that I would like to store in Cosmos as a single document (i.e. using embedded entities). I've followed the documentation to the best of my ability but something is going wrong. I have an object like the one below (this example is not my real code but it mimics what I'm trying to do ... not necessarily good design, but is just a concept at this stage):
public class BaseMessage
{
public Guid MessageId { get; set; }
public string Title { get; set; }
}
// Designed this way to allow for different types of messages
public class OneTypeOfMessage : BaseMessage
{
public MessageBody Body { get; set; }
}
public class MessageBody
{
public string Content { get; set; }
public Member Sender { get; set; }
}
public class Member
{
public Guid MemberId { get; set; }
public string FullName { get; set; }
public ContactMethods ContactMethods { get; set; }
}
public class ContactMethods
{
public string Email { get; set; }
public string Phone { get; set; }
public string Twitter { get; set; }
}
Then in my Config builder class ...
public void Configure(EntityTypeBuilder<OneTypeOfMessage> builder)
{
builder.ToContainer("MessageContainer");
builder.HasPartitionKey(x => x.Body.MessageType);
builder.HasKey(x => x.MessageId);
// Set up embedded relationships
builder.OwnsOne(x => x.Body, props =>
{
props.OwnsOne(x => x.Sender, props =>
{
props.OwnsOne(x => x.ContactDetails);
});
});
}
Now, when I run this, I get an error saying that The entity type 'Member' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' ....
I'm sure I'm missing something simple here, but some help would be greatly appreciated.
/cc @JeremyLikness to take a look
Ok, I've worked out what was going on. It turns out my IEntityTypeConfiguration classes were not being applied correctly in OnModelCreating, and therefore the configurations (such as Key, PartitionKey, etc) were not being applied.
This failed ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MessageConfigClass).Assembly);
}
This worked ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new MessageConfigClass());
}
@Dazfl Can you post a small, runnable repro where ApplyConfigurationsFromAssembly failed?
@ajcvickers ... as hard as I try, I can't seem to replicate the issue with a small, demo repo. This means there is something weird going on with the real code/project/solution I'm working on. It may have something to do with my repository code sitting in a separate Infrastructure project (trying to follow clean architecture principles). I'll keep digging to see what might be causing the issue and post what I find here.
@Dazfl Thanks for trying; don't worry too much about it if you can't repro.