问题
I have set up a self referential entity using EF Core which looks like this:
Entity
public class DetailType
{
public int DetailTypeId { get; set; }
public string Name { get; set; }
public int? ParentTypeId { get; set; }
public DetailType ParentType { get; set; }
public IEnumerable<DetailType> ChildTypes { get; set; }
}
Binding
modelBuilder.Entity<DetailType>()
.ToTable("detailtype")
.HasOne(x => x.ParentType)
.WithMany(x => x.ChildTypes)
.HasForeignKey(x => x.ParentTypeId);
I am retrieving these entities via an API and the current result looks something like this:
[
{
"detailTypeId": 20,
"name": "Money",
"parentTypeId": null,
"parentType": null,
"childTypes": null
},
{
"detailTypeId": 22,
"name": "Optional Extra",
"parentTypeId": null,
"parentType": null,
"childTypes": [
{
"detailTypeId": 42,
"name": "Extra Nights",
"parentTypeId": 22,
"childTypes": null
}
]
},
{
"detailTypeId": 42,
"name": "Extra Nights",
"parentTypeId": 22,
"parentType": {
"detailTypeId": 22,
"name": "Optional Extra",
"parentTypeId": null,
"parentType": null,
"childTypes": []
},
"childTypes": null
}
]
The problem I have with this is that the third item in the array is just the reverse of the second. Is there a way to avoid this so that I only have the parent -> child relationship rather than both parent -> child as well as child -> parent. The example above is a heavily cut-down version of what my API is actually returning so I want to reduce the unnecessary bloat as much as possible because there'll be a lot of relationships going on.
Ideally what I want is to just get rid of the ParentType property but still have the ChildTypes collection but I'm not sure how to define that in the model builder.
EDIT:
I have removed the fluent relationship as it's not needed. I've also tried the following:
var roots = this.Items.Where(x => x.ParentTypeId == null);
foreach (var root in roots)
{
root.ChildTypes = this.Items.Where(x => x.ParentTypeId == root.DetailTypeId);
}
return roots.ToList();
(this.Items
is the DbSet by the way)
However this requires changing ChildTypes
to an IQueryable
and when I do that I get the following exception:
The type of navigation property 'ChildTypes' on the entity type 'DetailType' is 'EntityQueryable' which does not implement ICollection. Collection navigation properties must implement ICollection<> of the target type.
回答1:
First things first - you don't need to specify this relation(s) in the model builder. It figures it out on its own.
Then regarding your question - the first thing, that comes to my mind (I don't know your entire dataset) is to get all the DetailType
objects, that have ParentTypeId == null
.
By this you will get the roots, and then, recursively build the tree
of child elements.
Doing this will clean-up your result, and you will see the structure as you want to see it.
来源:https://stackoverflow.com/questions/52502194/ef-core-one-way-self-referencing-entity-binding