插入数据库一对多关系.net core 3.1

问题描述 投票:0回答:1

我在表Race和Subrace中具有一对多关系。 1个种族可以具有多个子种族,但是1个种族只能具有1个种族。我已经完成了以下课程。

 public class Race
    {
        public int ID { get; set; }

        [Required]
        public string RaceName { get; set; }

        [Required]
        [StringLength(200)]
        public string RaceFeatures { get; set; }


        [JsonIgnore]
        public IList<SubRace> SubRaces { get; set; }


 public class SubRace
    {
        public int Id { get; set; }

        [Required]
        [StringLength(50, ErrorMessage = "Only 50 characters allowed")]
        public string SubRaceName { get; set; }
        [Required]
        [StringLength(400, ErrorMessage = "Only 400 characters allowed")]
        public string SubraceFeatures { get; set; }



        public int RaceID { get; set; }
        public Race Race { get; set; }
    }

但是,我无法弄清楚必须如何初始化此表中的值。这是我正在尝试执行的操作,但是在尝试运行时出现以下错误。

System.NullReferenceException:'对象引用未设置为对象的实例。'

API.Model.Race.SubRaces.get返回null。

if (!context.Races.Any())
            {
                var rc0 = new Race()
                {
                    RaceName = "Elf",
                    RaceFeatures = "Darkvision. +2 Charisma",

                };
                var sr1 = new SubRace()
                {
                    Race = rc0,
                    SubRaceName = "Wood",
                    SubraceFeatures = "+1 Wisdom",

                };
                rc0.SubRaces.Add(sr1);
                context.Races.Add(rc0);
                context.SaveChanges();
            }

我在这里做错了什么?我似乎无法弄清楚。

c# asp.net entity-framework api dbcontext
1个回答
1
投票

您缺少SubRaces初始化。

var rc0 = new Race()
            {
                RaceName = "Elf",
                RaceFeatures = "Darkvision. +2 Charisma",
                SubRaces = new List<SubRace>()
            };
© www.soinside.com 2019 - 2024. All rights reserved.