Two self-referencing one to many relations

c# entity-framework entity-framework-6


This is my first question, so if there are formatting issues or unclear formulations, please don't hestitate to tell me.

I have an entity called Item that, besides other properties has two links to other items("GlobalItem" & "DepositItem") in the same DBSet.

public class Item
    public int ItemID { get; private set; }

    public virtual Item GlobalItem { get; set; }

    public virtual Item DepositItem { get; set; }

    protected Item() { }

The mapping is done like so:

 public ItemMap()
        HasKey(o => o.ItemID);

        ToTable("Item", "dbo");

        // Relationships
        HasOptional(o => o.GlobalItem)
            .Map(m => m.MapKey("GlobalItemID"));

        HasOptional(o => o.DepositItem)
            .Map(m => m.MapKey("DepositItemID"));

The build process is successfull, but when I try to GetAll() the following Exception is thrown:

System.Data.Entity.Core.EntityCommandExecutionException: 'An error occurred while executing the command definition. See the inner exception for details.'

Inner Exception:

SqlException: Invalid column name 'DepositItem_ItemID'.

Invalid column name 'DepositItem_ItemID'.

Invalid column name 'DepositItem_ItemID'.

I know that this exception usually is caused by simple mapping errors, but in this case, i am stuck, as I made sure that the ColumnName and MapKey are correct, and all the usual workarounds like explicitly defining the DepositItemID in the entity and using .HasForeignKey(k = k.DepositItemID) instead of the former mapping definition did not change anything.

Does EF6 have a general problem with more than one self referencing virtual property? Can somebody explain to me, why the mapping key is ignored for DepositItem, but not ignored for GlobalItem? Can somebody find a flaw in my design?

Best regards and thank you for your efforts,

8/29/2018 2:36:08 PM

Popular Answer

The Item model and mapping are fine.

The issue was caused by an old navigation property, also called "DepositItem", in another entity which was not mapped in the database.

8/30/2018 12:12:36 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow