简体   繁体   中英

Accessing child object from parent object in EF Core

I've searched the whole net, but still I can't get this to work.

What I need is a simple list that looks like this:

  • ParentName1
  • ChildName1
  • ChildName2
  • ParentName2
  • ChildName3

I have one table of the Parent objects and one of the Child objects. In the table of Child objects, there is a foreign key ParentId.

Now, I use strongly typed ViewModel and Intellisense even suggests the Child properties through a Parent.Child.Property, but then when I run the program I get a "NullReferenceException: Object reference not set to an instance of an object.".

My Parent class looks like this:

    public class EmployeeArea
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        public int? StudioCode { get; set; }

        public string AreaName { get; set; }

        public List<EmployeeName> EmployeeNames { get; set; }
    }
}

And my Child class looks like this:

    public class EmployeeName
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ID { get; set; }

        public string Name { get; set; }

        public int AreaId { get; set; }
    }
}

Do I need to do something in the DbContext ModelBuilder? I welcome any help. Thank you!

Well, I can't see your query but I'd suggest the following. First, the foreign key should be :

public int EmployeeAreaId {get; set;}

then you have two options to get data from database. If you are using EF, then:

db.EmployeeArea.Include(e => e.EmployeeName).ToList();

which will return a list of employeeArea including the child list.

Using Linq will be like :

var employeeArea = (from e in db.EmployeeArea
                    select new EmployeeArea
                               {
                                  Id = e.Id
                                  // continue populating the model properties
                                  EmployeeNames = db.EmployeeName.Where(e => 
                                  e.EmployeeAreaId == e.Id).ToList(),
                               }).ToList()

Excuse any typo here. Hope it helps.

Be sure when looping through parents to check if their child list is null .

You have to first define the foreign key properly by overriding OnModelCreating or by convention:

public int EmployeeAreaId {get; set;}

If you are using strongly typed ViewModels you need to use EFCore Projections( https://entityframeworkcore.com/querying-data-projection ), the code would look something like this(replace with your viewmodel names):

db.EmployeeAreas.Select(e => new YourViewModel{
  ParentName = e.AreaName,
  ChildNames = e.EmployeeNames.Select(en => new List<string>{
    EmployeeName = en.Name
  }).ToList();
}).ToList();

If this were Json it would look like this:

[
  {
    ParentName : "ParentName1",
    ChildNames ; ["ChildName1","ChildName2"]
  },
  {
    ParentName : "ParentName2",
    ChildNames ; ["ChildName3"]
  }
]

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