C
C#12mo ago
Haqz

Prevent loading Many to Many relation further than first "level"

Hello, so currently i am struggling with .NET EF loading Many to Many (later called MtM) relation infinitely, which causes program to halt due to max depth being reached. I am looking for some way of avoiding that, but only after first "level". Example:
class A
{
public string PropertyA { get; set; }
public List<B> Bs = new();
}

class B
{
public string PropertyB { get; set; }
public List<A> As = new();
}

var test = new A{
PropertyA = "Test",
}

var test1 = new B{
PropertyB = "Test1",
}

test.Bs.Add(test1);
test1.As.Add(test);
class A
{
public string PropertyA { get; set; }
public List<B> Bs = new();
}

class B
{
public string PropertyB { get; set; }
public List<A> As = new();
}

var test = new A{
PropertyA = "Test",
}

var test1 = new B{
PropertyB = "Test1",
}

test.Bs.Add(test1);
test1.As.Add(test);
Assuming that these objects correspond to .NET EF models, this will cause infinite loop. test will have test1, that has test and so on. What i actually want is:
{
"PropertyA": "Test",
"Bs": [
{
"PropertyB": "Test1"
}
]
}
{
"PropertyA": "Test",
"Bs": [
{
"PropertyB": "Test1"
}
]
}
I've read that ChangeTracker.LazyLoadingEnabled = false;could help with that, but even having it set to false in my DbContext, it didnt help with the error. Only partial solution i found is to enable handling of loop references in Newtonsoft.JSON options, although it works, the issue of entities looping is still there For any help i thank in advance
1 Reply
Angius
Angius12mo ago
.Select() into a DTO
Want results from more Discord servers?
Add your server