0

Two models:

public class Item
{
    public int Id { get; set; }
    public string Title { get; set; }

    public int? StorageId { get; set; }
    public virtual Storage? Storage { get; set; }
}

public class Storage
{
    public int Id { get; set; }
    public string StorageName { get; set; }

    public virtual ICollection<Item>? Items { get; set; }
}

I want to create a table where I could see a storage name for every item. How to achieve that using web api? Is there any LINQ method or I should create some more properties in Item model?

I am getting a JSON possible cycle error if I use this:

public async Task<ActionResult<IEnumerable<Item>>> GetItems()
{
    var item = await _context.Items.Include(c => c.Storage).ToListAsync();

    return item;
}

I saw the way to avoid cycle error using

builder.Services
    .AddControllersWithViews()
    .AddJsonOptions(options => options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

But not sure it is a good practice..

Thanks in advance

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
desmondische
  • 186
  • 13
  • Good practice is to create additional DTO class which represents result data and build this entity via `Select` or via Automapper's `ProjectTo`. Then circular references will never appear. Anyway you can add `AsNoTracking()` to the query and EF will not fixup circular reference properties. – Svyatoslav Danyliv Mar 29 '22 at 18:59
  • @SvyatoslavDanyliv could you please provide some code examples? I am trying to figure out how to achieve my goal all day already :/ – desmondische Mar 29 '22 at 19:11
  • Try using `AsNoTracking` first. Then read several articles about DTO (Data Transfer Object) – Svyatoslav Danyliv Mar 29 '22 at 19:15
  • Still seeking for help! – desmondische Mar 29 '22 at 20:11
  • Does this answer your question? [How to resolve System.Text.Json.JsonException: A possible object cycle was detected in Entity Framework?](https://stackoverflow.com/questions/70603118/how-to-resolve-system-text-json-jsonexception-a-possible-object-cycle-was-detec) – Ruslan Gilmutdinov Mar 31 '22 at 08:47

0 Answers0