Anthony
Anthony

Reputation: 135

EFCore Disable related data from loading it's related data?

let's say i have 2 models.

Model 1

public class model1
{
   public string Name {get;set;}
   public virtual model2 relatedModel2 {get;set}
}

Model 2

public class model2
    {
       public string Name {get;set;}
       public virtual ICollection<model1> relatedModel1 {get;set;}
    }

now every time i try to get model 1 and include model 2. model 2 also includs all model 1 related data as stated here.

now i need to disable that. is that possible? here is how i query the data.

context.model1.Include(a => a.model2).toList();

this is the result i get.

[
  {
     name: 'blah blah blah',
     relatedModel2: {
         name: 'blah balh blah',
         relatedModel1: [{...}, {...}, {...}, {...}]
     }
  }
]

i need to remove relatedModel1 from relatedModel2.

Update (forgot to include during first time posting this): i already have this setup.

services.AddControllers()
            .AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

Upvotes: 0

Views: 108

Answers (2)

Anthony
Anthony

Reputation: 135

apparently, i was comparing this to my previous project which uses aspcore 2.2 version and indeed they are behaving exactly the same.

the only thing i didn't observe is the difference between retrieving all data and few data.

when i retrieve only a few data i get results and then the related data may be populated or not, it depends whether those data are related to each other. for example.

model 1 data

[
  {
    id: 1,
    name: "george",
    relatedModel2: 1
  },
  {
    id: 2,
    name: "jason",
    relatedModel2: 1
  },
  {
    id: 3,
    name: "michael",
    relatedModel2: 1
  },
  {
    id: 4,
    name: "luke",
    relatedModel2: 2
  }
]

model 2

[
  {
    id: 1,
    name: "greg"
  },
  {
    id: 2,
    name: "martin"
  }
]

so when i try to retrieve all data. it also populates all related data. but when i try to retrieve let's say model1 with id in (1,2).

[
  {
    id: 1,
    name: "george",
    relatedModel2: {
      id: 1,
      name: "greg",
      relatedModel1: [
        {
          id: 2,
          name: "jason"
        }
      ]
    }
  },
  {
     id: 2,
     name: "jason",
     relatedModel2: {
       id: 1,
       name: "greg",
       relatedModel1: [
         {
           id: 1,
           name: "george"
         } 
       ]
    }
  }
]

Upvotes: 0

Mridusmita Deka
Mridusmita Deka

Reputation: 345

Use this in ConfigureServices method-

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

Or Add [JsonIgnore] on top of

public virtual ICollection<model1> relatedModel1 {get;set;}

Upvotes: 1

Related Questions