简体   繁体   中英

insert into database one to many relationship .net core 3.1

I have a one to many relationship of the tables Race and Subrace. 1 Race can have multiple subraces but 1 subrace can have only be 1 race. I have made the following classes.

 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; }
    }

I can't however figure out how I have to initialize values in this table. This is what I'm trying to do but I get the following error when trying to run.

System.NullReferenceException: 'Object reference not set to an instance of an object.'

API.Model.Race.SubRaces.get returned 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();
            }

What am I doing wrong here? I can't seem to figure it out.

You are missing the SubRaces initialization.

var rc0 = new Race()
            {
                RaceName = "Elf",
                RaceFeatures = "Darkvision. +2 Charisma",
                SubRaces = new List<SubRace>()
            };

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