Include parent and child in query?

asp.net-core c# entity-framework-core

Question

I have two entities with one to many relationship like this:

Customer 1......* Booking

 public class Customer
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Booking> Bookings { get; set; }
    }


  public class Booking
    {
        [Key]
        public int Id { get; set; }
        public string Title{ get; set; }
        public DateTime BookingDate { get; set; }
        public int? CustomerId { get; set; }
        public Customer Customer { get; set; };

    }

If _context being DbContext, following two queries ended up in circular dependency.

_context.Customers.Include(x=> x.Bookings).ToList();

OR

_context.Bookings.Include(x=> x.Customer).ToList();

Question is how can we query these interdependent relationships if we have to include entity A in B's query and vice versa?

1
0
11/29/2016 9:46:54 AM

Popular Answer

One possible solution to above problem in my case as I was using Asp.Net Core was to tell in MVC options to handle reference loops as follows:

 services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                });

I have raised an issue with EF core team to answer if reference looping should be handled on consumer end or it should be handled by EF Core. Will update the answer once get a response.

0
11/29/2016 8:24:11 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow