0

I'm currently using EF Core and I have 3 tables

Campaign
CampaignStation
Station

CampaignStation is a intermediate table between Campaign and Station

Campaign table:

public class Campaign
{
    public int CampaignId { get; set; }

    public string Name { get; set; } = string.Empty;

    public ICollection<CampaignStation> Stations { get; set; } = new List<CampaignStation>();

 }

public void Configure(EntityTypeBuilder<Campaign> builder)
    {
        builder.HasKey(x => x.CampaignId);
        builder.Property(x => x.Name).IsRequired().HasMaxLength(250);
        builder.HasMany(x => x.Stations).WithOne(y => y.Campaign);
    }

So one campaign can have multiple Stations, that is why I have an intermediate table as:

public class CampaignStation
{
    public int CampaignStationId { get; set; }

    public int? CampaignId { get; set; }

    [ForeignKey(nameof(CampaignId))]
    public Campaign? Campaign { get; set; }

    public int? StationId { get; set; }

    [ForeignKey(nameof(StationId))]
    public Station? Station { get; set; }
}


public void Configure(EntityTypeBuilder<CampaignStation> builder)
    {
        builder.ToTable("CampaignStations");
        builder.HasKey(x => x.CampaignStationId);
        builder.HasOne(x => x.Campaign);
        builder.HasOne(x => x.Station);
    }

Get Service:

return await _db.Campaigns
            .Include(a => a.Agency)
            .Include(s => s.Stations)
            .ToListAsync();

As you can see in the following image the Get controller returns data correctly

![enter image description here

But in the chrome console network tab it returns status failed

enter image description here

So I remove the Stations ICollection from the campaign table to see if it is the problem.

And now the controller is working!, But I can not understand why the collection not working? I need the collection, what I'm doing wrong adding it?

0

1 Answer 1

1

Serializing your database entities is asking for trouble. In particular the entity graph has cycles, so it's valid to have code like:

var someCampaign = results.First();
someCampaign.Stations.First().Campaign.Stations.First().Campaign.Stations.First().Campaign.Stations.First().Campaign.Stations.First().Campaign.Stations.First() //..... and so on, forever

The JSON serializer doesn't know to stop just because the first Station on the .Campaign.Stations is the same station it just visited; it's just trying to build a JSON from every property on every object it can find. If a Station X points to a Campaign Y, which (somewhere in its stations list) points to that same Station X then you've got a cyclical reference. It'll just start visiting referenced objects, making a JSON like this:

{
  CampaignId: 1,
  Name: "Campaign 1",
  Stations: [
    {
      StationId: 1,
      Name: "Station 1"
      Campaign: 
        {
          CampaignId: 1,        //REPEATED!
          Name: "Campaign 1",
          Stations: [
            {
              StationId: 1,
              Name: "Station 1"
              Campaign: {
                  ....            //Campaign 1 REPEATED! (getting forever deeper and deeper here)
            }
          ]
        }
    }
  ]
}

enter image description here

Resolving this cycle can be done in different ways:

  • Typically we have a different set of objects that we serialize out to the front end (viewmodels) that are populated from the database entities. These objects' relational navigations don't have cycles (or if they could have cycles the cycle is not completed by whatever strategy populates the data into them), so the serializer doesn't get stuck on them

  • If we really do want to serialize our DB entities, we can tell the serializer to keep track of objects it's seen before, and don't serialize them again (so it doesn't get stuck in a loop), or we tell EF not to track relationships between entities, so EF doesnt wire the object graph up in such a way that it contains cycles

  • Another option for serializing DB entities is to disconnect the navigation, from e.g. a Campaign back to a Station, by looping over the someCampaign.Stations list and setting the .Campaign of every Station therein to null. This is something you need to do after you download the data, but before it is serialized. You thus end up with e.g. a Campaign that refers to 10 Stations, but none of those stations refer back to the owning Campaign


Edit:

So you pick option 1, and you have some classes like these (these are records, because they make life easy, but you can just as easily use full classes):

public record CampaignViewModel(int CampaignId, string Name, List<StationViewModel> Stations);

public record StationViewModel(int StationId,string Name);

And you have a routine that populates them in your controller:

var result = ...//existing code

var vm = result.Select(c => new CampaignViewModel(
  c.CampaignId, 
  c.Name, 
  c.Stations.Select(cs => new StationViewModel(cs.StationId, cs.Station.Name)).ToList()  //used cs because c.Stations is a list of CampaignStation type object
)).ToList();

return View(vm);

We typically call this mapping, and there exist tools like AutoMapper that can do it for you, because writing mapping code is boring, but the critical thing here is that our interconnected db entities graph is turned into a graph of objects that is one way: a collection of CampaignViewModel where each might have a list of StationViewModel obejcts, but none of those point back to a CampaignViewModel

A significant benefit of using a set of objects targeted at your front end's needs is that these objects can contain just the data that the front end wants to use, and things like calculation results that you don't want to have in your DB objects. One of the great pitfalls in trying to reduce coding by sending your DB entities to the front end is we then think "ah.. let's get the front end to send a DB entity back, and then I'll just create an EF context, fake that it's seen that entity before and attach it so I can get it to a DB update easily.." - and that really opens the can of worms with regards to data security; you don't necessarily want to send all the data in your DB to your front end, nor allow your FE to supply everything the DB knows about

6
  • I'm confused there. Do you have a reference or example of how can I serialize the object in the view model or how to achieve that?
    – Jesus
    Commented Nov 29, 2022 at 18:20
  • You need to pick which of the 3 options you go for. I do option 1, serializing objects that are designed for the front end's needs (and they don't have cycles) Commented Nov 29, 2022 at 18:22
  • Yes, I think is the easiest one, so I will go for option 1
    – Jesus
    Commented Nov 29, 2022 at 18:30
  • I added some note at the bottom about how we could do an option 1 Commented Nov 29, 2022 at 18:51
  • For some reason it didn't work, I will check more deep
    – Jesus
    Commented Nov 29, 2022 at 19:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.