Search code examples
entity-framework-coredomain-driven-design

How to map in EF Core a collection of child entities when children has not ID of the parent?


I have this:

Class Order
{
    long ID;
    ...
}

Class Item
{
    long Id;
    IdProduct;
    decimal Amount;
    ...
}

How could I map this in EF Core using fluent API? Or is it not possible and I have to have in the childs a property for the ID of the parent? But in my case, from a point of view of DDD I don't need this property in the children because the children has not need to know about the parent.

Thanks.


Solution

  • Assuming you have a collection of 'Item' in Order ...

    class Order
    {
        public long ID { get; set; }
        public List<Item> Items { get; set; }
    }
    

    Order Config:

    builder.HasMany<Item>(p => p.Items)
       .WithOne()
       .HasForeignKey("OrderId");
    

    This will create FK property OrderId on the Item without it being explicitly declared in the class itself.