cofoundry
cofoundry copied to clipboard
How to create a custom entity
Sorry, but I'm lost in the documentation. I can find examples of defining custom entities and querying custom entities and it works for me - I can create bookings in the admin interface and list them in a separate page.
I can also finde examples of commands that create custom data (not custom entities) like CatLike
in the SPA example - but how do I add an instance of a custom entity to the database programmatically? Could you please clarify that in the docs?
I have a booking data model:
public class BookingDataModel : ICustomEntityDataModel
{
public DateTime? ArrivalDate { get; set; }
... more properties ...
}
I also have a web-form for submitting a booking request. I can also make a command as well as a command handler. But what should I do in the command handler?
public class AddBookingCommandHandler : ICommandHandler<AddBookingCommand>
{
private readonly CofoundryDbContext _dbContext;
public AddBookingCommandHandler(CofoundryDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task ExecuteAsync(AddBookingCommand command, IExecutionContext executionContext)
{
var booking = new BookingDataModel();
// populate booking data model with input from command
// *** THIS IS WRONG ***
// Booking data model implements ICustomEntityDataModel - but it is not a CustomEntity in itself.
await _dbContext.CustomEntities.AddAsync(booking);
// SO ... how to add the booking data model?
await _dbContext.SaveChangesAsync();
}
}
Nothing like writing down your issue that makes you figure out your problems all by yourself.
I realized that I needed to issue an AddCustomEntityCommand
and then I had a place to pass my BookingDataModel (ICustomEntity):
var myBooking = new BookingDataModel { ... }
using (var scope = ContentRepository.Transactions().CreateScope())
{
var addCustomEntityCommand = new AddCustomEntityCommand
{
CustomEntityDefinitionCode = BookingCustomEntityDefinition.DefinitionCode,
Model = myBooking,
UrlSlug = "Booking",
Title = "Booking" + request.Booking.ArrivalDate?.ToString("d"),
Publish = true,
PublishDate = DateTime.Now
};
await ContentRepository.ExecuteCommandAsync(addCustomEntityCommand);
await scope.CompleteAsync();
}
May I suggest that you add that knowledge to the online documentation?