简体   繁体   中英

Json response does not contain all the navigation properties EntityFramework Core and ASP .NETCore Web API

I have migrated from Entity Framework 6 to EF Core and also Web Api .net framework to .net core.

I have many to many relationship that I have set up as follows

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        var instrumentsToPlaces = modelBuilder.Entity<InstrumentPlace>();
        instrumentsToPlaces.ToTable("InstrumentsToPlaces");
        instrumentsToPlaces.HasKey(x => new { x.PlaceId, x.InstrumentId });

        instrumentsToPlaces.HasOne(i => i.Instrument)
            .WithMany(p => p.InstrumentsPlaces)
            .HasForeignKey(ip => ip.InstrumentId);

        instrumentsToPlaces.HasOne(p => p.Place)
            .WithMany(i => i.InstrumentsPlaces)
            .HasForeignKey(ip => ip.PlaceId);


        var instrumentsToStyle = modelBuilder.Entity<InstrumentStyle>();
        instrumentsToStyle.ToTable("InstrumentsToStyles");
        instrumentsToStyle.HasKey(x => new { x.StyleId, x.InstrumentId });

        instrumentsToStyle.HasOne(i => i.Instrument)
            .WithMany(s => s.InstrumentStyles)
            .HasForeignKey(si => si.InstrumentId);

        instrumentsToStyle.HasOne(s => s.Style)
            .WithMany(i => i.InstrumentStyles)
            .HasForeignKey(si => si.StyleId);

    }

I have included the navigation properties in the repository method as follows

        public Instrument GetInstrumentByName(string name)
    {
        using (var starsAndCatzDbContext = new StarsAndCatzDbContext())
        {
            var instrument = _starsAndCatzDbContext.Instruments
            .Include(a=>a.InstrumentsPlaces)
            .ThenInclude(a=>a.Place)
            .Include(a=>a.InstrumentStyles)
            .ThenInclude(a=>a.Style)
           .FirstOrDefault(i => i.Name == name);


            return instrument;

        }


    }

Here are the classes

public class Instrument {
    public int Id { get; set; }
    public string Name { get; set; }

    public  virtual ICollection<InstrumentPlace> InstrumentsPlaces { get; set; }
    public virtual ICollection<InstrumentStyle> InstrumentStyles { get; set; }
}

 public class InstrumentPlace
{
    public int InstrumentId { get; set; }
    public Instrument Instrument { get; set; }
    public int PlaceId { get; set; }
    public Place Place { get; set; }
}

     public class InstrumentStyle
{
    public int InstrumentId { get; set; }
    public Instrument Instrument { get; set; }
    public int StyleId { get; set; }
    public Style Style { get; set; }
}

    public class Style {
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<InstrumentStyle> InstrumentStyles { get; set; } 
}

        public class Place {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Division { get; set; }
    public int Tier { get; set; }
    public string State { get; set; }
    public string Postcode { get; set; }
    public float? Latitude { get; set; }
    public float? Longitude { get; set; }
    public virtual ICollection<InstrumentPlace> InstrumentsPlaces { get; set; }
}

The WebAPI method to be called is

        [HttpGet("GetInstrumentByName/{suburb}/{instrument}"), Produces("application/json")]
    public Instrument GetInstrumentByName(string suburb, string instrument)
    {
        try
        {
            var result = _instrumentRepository.GetInstrumentByName(instrument);
            return result;
        }
        catch (Exception ex)
        {

            _logger.LogError(ex.Message);
            return new Instrument();
        }

    }

When I send the request to "/api/instruments/west-end/guitar" I get the expected result when I place a breakpoint before sending the response as follows

在此处输入图片说明

As you notice, the Navigation properties are loaded (when I expand the collections I can see all the properties being loaded as well). However the json response I receive is the following

在此处输入图片说明

Any suggestions or am I missing something here?

Thank you all in advanced

Thanks @H. Herzl for giving me a hint.

The solution was found in this other question

services.AddMvc().AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

https://stackoverflow.com/a/40501464/1513346

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