简体   繁体   中英

C# entityframework save self-reference id in same table

This may seem silly question. Sorry about this :)

I am using C# Entityframework to store an entity in a sqlserver table. I have the following sample class:

public calss Item
{
    public int ItemId {get;set;}
    public int? ParentId {get;set;}
    public string Column1 {get;set;}
    public string Column2 {get;set;}
}

Expected Data:

ItemId  ParentId    Column1     Column2
100     null        paaaaaa     null
101     100         null        Childdddd

i am saving the entities in memory and finally call context.savechanges(). How do i get the id of the parent when i save both the records at one save?

thanks

You can achieve this like that :

   public class Item
    {
        public int ItemId {get;set;}
        public int? ParentId => Parent?.ItemId;
        public string Column1 {get;set;}
        public string Column2 {get;set;}
        public Item Parent {get;set;}
    }

First of all I think you shouldn't do it on save, in my opinion it's better do it when you create child.

Create method that finds parents by your logic. (it's hard to answer not knowing how do you determine which one is parent if there is more then one)

void Save() 
{
   SetParents();
   context.savechanges();
}

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