简体   繁体   中英

EF4 Code First: Parent/Child relationship in same table, how to get inverse property?

I have a class that gets arranged into a hierarchy, such as this:

class Item
{
    [Key]
    public int ID {get;set;}
    public string PropA {get;set;}
    public string PropB {get;set;}

    public Virtual ICollection<Item> Children {get;set;}
}

This works great, and EF creates a Item_ID key to identify the parent. I am exporting this data via my MVC app and need to access this key however.

How can I access the Parent ID, from an Item?

I tried [InverseProperty] tag, but it seemed like it wanted to create yet another key -- How can I get it to use the existing Item_ID field that is already in my database and working properly with my Children navigation property?

Thanks!

Okay, I had to change the name of my database column frmo Item_ID to Parent_ID manually, then everything worked. I have the following:

[InverseProperty("Parent")]
public virtual ICollection<Item> Children { get; set; }

[InverseProperty("Contents")]
public virtual Item Parent { get; set; }

I think you would have to add a

public virtual Item Parent {get;set;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM