I'm struggling with a sub table many to many relationship. EF6
Table1:
Id int
Name string
Table2:
Id int
ParentId int fk
ChildId int fk
Table2 has two links to Table1 in it - ChildId, and ParentId which are Foreign keyed to Id in Table1. Entity Framework will update the ParentId correctly when called, but updates the ChildId to the ParentId of the Table1 Id?
public partial class GeographicPolygon : IPublishingEntity
{
public GeographicPolygon()
{
this.GeographicPolygonLinkParents = new HashSet<GeographicPolygonLink>();
this.GeographicPolygonLinkChildren = new HashSet<GeographicPolygonLink>();
}
public int Id { get; set; }
public System.Guid InternalId { get; set; }
public string Name { get; set; }
[InverseProperty("GeographicPolygonParent")]
public virtual ICollection<GeographicPolygonLink> GeographicPolygonLinkParents { get; set; }
[InverseProperty("GeographicPolygonChild")]
public virtual ICollection<GeographicPolygonLink> GeographicPolygonLinkChildren { get; set; }
}
public partial class GeographicPolygonLink : IEntity
{
public int Id { get; set; }
public int ParentId { get; set; }
public int ChildId { get; set; }
[ForeignKey("ChildId")]
public virtual GeographicPolygon GeographicPolygonChild { get; set; }
[ForeignKey("ParentId")]
public virtual GeographicPolygon GeographicPolygonParent { get; set; }
}
The data being passed in.
{
"Id": 3,
"Name": "New GeoPoly 2",
"GeographicPolygonLinkChildren": [
{
"ParentId": 3,
"ChildId": 10,
},
{
"ParentId": 3,
"ChildId": 11,
}
]
}
The call to the update is:
var internalId = Guid.Parse(document.InternalId);
var existing = await context.Set<TTarget>().FirstOrDefaultAsync(x => x.InternalId == internalId);
if (existing == null)
{
existing = new TTarget {CreatedDate = DateTime.Now};
context.Set<TTarget>().Add(existing);
}
mapper.Map(document, existing);
await context.SaveChangesAsync();
I look at 'existing' before the update and the Id's are all correct. ChildId's 10 and 11.
After the SaveChangeAsync the database has:
ID ParentId ChildId
320 3 3
321 3 3
I cannot get the ChildId to update correctly even with the annotations.
In my model builder I have:
builder.EntitySet<GeographicPolygonModel>("GeographicPolygon");
builder.EntitySet<GeographicPolygonLinkModel>("GeographicPolygonLink");
My edmx has:
<EntityType Name="GeographicPolygon">
<Key>
<PropertyRef Name="Id" />
</Key>
<Property Name="Id" Type="Int32" Nullable="false" />
<Property Name="Name" Type="String" Nullable="false" />
<NavigationProperty Name="GeographicPolygonLinkParents" Relationship="DataContext.fkGeographicPolygonLinkParentId_GeographicPolygon" FromRole="GeographicPolygon" ToRole="GeographicPolygonLink" />
<NavigationProperty Name="GeographicPolygonLinkChildren" Relationship="DataContext.fkGeographicPolygonLinkChildId_GeographicPolygon" FromRole="GeographicPolygon" ToRole="GeographicPolygonLink" />
</EntityType>
I've looked and looked, but nothing I have tried has worked?
Any ideas please?