Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
I have the following class:

public class Parent
{
    private int Id;
    private String Title;
    
}
And the following objects list:

id:1,title:"Europe"
id:2,title:"Western Europe"
id:3,title:"Eastern Europe",
id:4,title:"Germany" 




i want to store that list in data base table as
id   parentid      title
1      null        Europe
2        1        Western Europe
 3        1       Eastern Europe
Posted

In your present structure,there is no way to really know that Europe is the parent of Eastern and Western Europe.

This is what you could try -
C#
public class Parent
{
    private int Id;
    private String Title;
}
public class Child : Parent
{
    private int ParentId;
}


Once you follow this structure, you can run through all Child instances and insert the parent id where it is not null.
 
Share this answer
 
v3
Your current class does not have a property for holding parent id. You have to modify your class to have ParentId property in it. Your new class should look like,
C#
public class Parent
{
    private int Id;
    private int? ParentId;
    private String Title;
    
}

You can see that I used nullable int for ParentId property, as it can be null for parents like in your case Europe.

When you insert the value to DB, check whether ParentId is null and insert value based on that.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900