I'm using Entity Framework Core.
My model classes are:
public class Material
{
public long Id { get; set; }
public string Name { get; set; }
public double Weight { get; set; }
public long? ParentId { get; set; }
public Material Parent { get; set; }
public State State { get; set; }
}
public class State
{
public long Id { get; set; }
public string Name { get; set; }
}
My problem is that EF will load Parent
entity even I don't include it in my query.
public IEnumerable<Material> GetAllMaterials()
{
return _context.Materials
.Include(m => m.State)
.ToList();
}
Related configuration is this.
builder.Entity<Material>()
.HasOne(m => m.Parent)
.WithMany()
.HasForeignKey(m => m.ParentId);
builder.Entity<Material>()
.HasOne(m => m.State)
.WithMany();
Is there away that I can prevent this happens? I need only parentId
, not the whole entity.
I have tried the [NotMapped]
attribute and virtual for Parent property.
Here is example json what my controller is returning http://paste.dy.fi/5xa?clr=json&style=default&row=1&tabsize=0
EDIT: More researching: If I make this query:
_context.Materials
.Include(m=>m.Location)
.Include(m => m.State)
.Include(m => m.Status)
.Include(m => m.RemovalMethod)
.Where( m =>m.Parent!= null)
.ToList();
I will not get parents. And they are not coming with child entities. JSON result is this http://paste.dy.fi/Ozk
Here is one more example how this is working:
_context.Materials
.Include(m=>m.Location)
.Include(m => m.State)
.Include(m => m.Status)
.Include(m => m.RemovalMethod)
.Include(m => m.Parent)
.Where( m =>m.Parent!= null)
.ToList();
JSON result is this http://paste.dy.fi/Oie This last one make sence because I include Parent.