首页 > 解决方案 > 为数据库插入优先级

问题描述

由于表具有外键约束,我需要创建一个服务以特定顺序将数据插入数据库。删除约束并重新添加它不是首选,因此我尝试先插入子数据,然后再插入父数据。

用一个例子来总结一下

必须先插入能量,然后是泰坦,然后是玩家。

我试图创建一个网格来表示一个类是否有另一个类引用。

class Program
    {
        static void Main(string[] args)
        {

            Type [] tables_toScan = new Type[] { typeof(Titan), typeof(Player), typeof(Energy) };

            int table_scan_length = tables_toScan.Count();

            int[,] grid_table = new int[table_scan_length, table_scan_length];

            IDictionary<Type, int> position_space = new Dictionary<Type, int>();
            for (int i = table_scan_length-1; i > -1; i--)
            {
                position_space.Add(tables_toScan[i], i);
            }

            foreach (var type in tables_toScan)
            {
                PropertyInfo[] propertyInfos = type.GetProperties();
                IEnumerable<Type> typeList = propertyInfos.Select(x => x.PropertyType).Distinct();

                foreach (var currentPropertyType in typeList)
                {
                    if (tables_toScan.Contains(currentPropertyType))
                    {
                        grid_table[position_space[currentPropertyType], position_space[type]] = 1;
                    }
                    else if (currentPropertyType.IsGenericType &&
                      currentPropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(currentPropertyType))
                    {
                        var collectionUnderLyingType = currentPropertyType.GetGenericArguments()[0];
                        if (tables_toScan.Contains(collectionUnderLyingType))
                        {
                            grid_table[position_space[collectionUnderLyingType], position_space[type]] = 1;
                        }
                    }
                }
            }
            Console.ReadKey();
        }
    }

    class Titan
    {
        public int id { get; set; }
        public IList<Energy> energy { get; set; }
    }

    class Player
    {
        public int id { get; set; }
        public Titan titan { get; set; }
    }

    class Energy
    {
        public int id { get; set; }
        public string color { get; set; }
    }

我想为给定的场景订购课程:

打印网格给出

           Titan      Player     Energy
Titan      0          1          0
Player     0          0          0
Energy     1          0          0

标签: c#database

解决方案


推荐阅读