如何在列表C中生成父子关系 [英] How Do I Make Parent Child Relation Ship In List C#

查看:93
本文介绍了如何在列表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希望将该列表存储在数据库表中





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

推荐答案

在你目前的结构中,没有办法真正知道欧洲是东欧和西欧的母体。 br />


这是你可以尝试的 -

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 -
public class Parent
{
    private int Id;
    private String Title;
}
public class Child : Parent
{
    private int ParentId;
}





一旦你遵循这个结构,你可以运行所有的Child实例并插入父ID null。



Once you follow this structure, you can run through all Child instances and insert the parent id where it is not null.


您当前的类没有用于保存父ID的属性。您必须修改您的类以在其中包含ParentId属性。你的新课应该是这样的,

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,
public class Parent
{
    private int Id;
    private int? ParentId;
    private String Title;
    
}



你可以看到我在ParentId属性中使用了nullable int,因为对于像你的情况那样的父母,它可以为null。 br />


将值插入DB时,检查ParentId是否为空并根据该值插入值。


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.


这篇关于如何在列表C中生成父子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆