I have the following entities:
public class Cart
{
public required Guid Id { get; init; }
public required List<CartProduct> Products { get; init; }
}
public class CartProduct
{
public required Guid ProductId { get; init; }
public required int Quantity { get; set; }
}
I’m configuring the Cart
entity as follows:
public class CartEntityTypeConfiguration : IEntityTypeConfiguration<Cart>
{
public void Configure(EntityTypeBuilder<Cart> cartEntity)
{
cartEntity.ToTable("carts");
cartEntity
.HasKey(cart => cart.Id)
.HasName("pk_carts");
cartEntity
.Property(cart => cart.Id)
.HasColumnName("id");
cartEntity.OwnsMany(
cart => cart.Products,
products => products.ToJson("products")
);
}
}
But it results in the "products"
property considered nullable. Here’s a code snippet from generated migration:
migrationBuilder.CreateTable(
name: "carts",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
products = table.Column<string>(type: "jsonb", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_carts", x => x.id);
}
);
Notice how the "products"
column is marked with nullable: true
.
I’ve tries the following two options:
cartEntity.OwnsMany(
cart => cart.Products,
products => products.ToJson("products")
);
cartEntity
.Navigation(cart => cart.Products)
.IsRequired();
and
cartEntity
.OwnsMany(
cart => cart.Products,
products => products.ToJson("products")
)
.Navigation(cart => cart.Products)
.IsRequired();
But with both approaches I’m getting the same error: Unable to create a 'DbContext' of type ''. The exception ''Cart.Products' cannot be configured as required since it was configured as a collection.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
.
Is there a way to make this property not-nullable?
P.S.: Yes, I could just go and edit the generated migration and model snapshot, but I would like to have a way to configure this using Fluent API.