Multi dimensional relationship looses the relation with wrapper

走远了吗. 提交于 2019-12-02 00:12:48

When you add Container instance to the context, the EF Core relationship fixup process will examine the Items collection and will automatically assign Item.Container property (and the FK). However the lower level items and neither contained in Items collection nor have Container property assigned, so EF will try to use whatever value FK contains (since it's non nullable, it will use the 0 - note that 0 is valid value for non generated key).

If you are wondering why it isn't assigning the top Container recursively, the answer is - because the model does not imply such behavior. From relational standpoint there is no relation between ParentItem.Container and ChildItem.Container - it's pretty valid they to have different values. If the intention is that all child items share the root item container, then the entity model contains redundancy - Container property/FK must be nullable and assigned only for the root items (basically mutually exclusive with ParentItem).

If you want to keep it the way it is, there is no way to express your intent to EF Core (or relational database in general). So you need to enforce that constraint manually by either adding lower level items to the container Items collection, or the easier - assign container instance to their Container property:

var container = new Container();
container.Items = new List<ContainerItem>
{
    new ContainerItem
    {
        ChildItems = new List<ContainerItem>
        {
            new ContainerItem
            {
                Container = container // <-- do the same for all non direct items
            }
        }
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!